You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
code_samples:
- identifier: my_sample_idtype: SINGLE_RPC# SINGLE_RPC code samples invoke one API method.## The API method is defined here, including the API, version, etc.#api_method:
api: google.cloud.fooversion: v1default_version: trueservice: FooServicemethod: ListFoossignature: [parent, filter_options]comment: ["Note: May take up to 5000ms to respond with value."]
API Name
string (required)
Name of API, e.g. google.cloud.language
API Version
string (required)
Version of the API to call, e.g. v1beta1
Default Version
bool default: false
Some generators output different code for the default version of the API, usually the latest stable version. For example, explicit version numbers may not be used in imports.
Service Name
string (required)
Name of service object of API, e.g. LanguageService
Method Name
string (required)
Name of rpc method on service, e.g. ClassifyText
Method Signature
List<string> (optional)
Defines the method signature to use. Each item provides is the name of a field on the request message. A matching signature must be defined on the rpc via option(google.api.method_signature). If not specified, default signature is used (usually passing the whole request object).
Comment
List<string> (optional)
Describes this API invocation, useful for non-trivial or obvious method signatures. Intended to be output in source code as comment.
code_samples:
- id: my_unique_sample_idtype: SINGLE_RPCdescription: "This sample demonstrates calling the Foo API"request_config:
fields:
# Basic configuration of field on request message# with literal value.
- field: max_resultsvalue: 10# Add description to field, intended to be displayed# as a comment on the field assignment.
- field: filterdescription: | Provide a filter for Foo objects (optional) e.g. name~Awesomevalue: "[FILTER]"# Provide an input_parameter name.# Intended to add a parameter to the sample method/function# and allow users to provide their own values, e.g. via CLI.
- field: parent.projectvalue: "[PROJECT]"input_parameter: project_iddescription: "Your Google Cloud Project ID"# Define literal value for repeated string field
- field: categoriesvalue:
- Technology
- Sciencedescription: "List of categories to search within"# Define literal value for map<string,int> field
- field: limit_optionsvalue:
min: 0max: 100# Read local file into a text field
- field: filters.csv_filter.file_contentinput_parameter: text_file_pathinput_type: LOCAL_FILE# Read local file into a bytes field
- field: filters.audio_query.contentinput_parameter: audio_file_pathdescription: "Path to local audio file, e.g. dir/audio.wav"input_type: LOCAL_FILE
Field Name
string
Name of field on request message. May reference a deeply nested field, e.g. config.query_options.limit.
Description
string
Description of this field and what it is being used for. Typically used as parameter description comment.
Value
Any string, bool, int List<string> Map<string,int>
Represents the default value to configure this sample. For simple types (string, bool, numerics), this is a native value. For enum types, this is either an int or string reference to enum value. For repeated types, this is a List of values. For map types, this is a Dictionary of values. For message types, this is a List of request fields for that message.
Input Parameter
string
(Optional) Name to use for developer to provide this value as input. If provided, the sample should be parameterized to allow for input. Value often used as the variable name for generated method or CLI.
Input Type
RequestFieldInputType
Used to denote special input handling, e.g. byte fields on messages can be populated from a provided string to a local file path using RequestFieldInputType.LOCAL_FILE
code_samples:
- id: my_unique_sample_idtype: SINGLE_RPCdescription: "This sample demonstrates calling the Foo API"# (Optional) define a return valuereturn_value: $response.foo_entities# (Optional) define statements for error handlingon_error:
- print: ["API Error {}", $response.error.message]# Define statements to generate which run after a successful API response.on_success:
# Define a code comment.# Arguments are used to include variable names in comment# using the correct casing idiomatic to the language.# This will print ListFoo in C#, listFoo in Node.js, list_foo in Python.# The variable is an arbitrary snake_case_string and does not need to be defined.
- comment:
- "Listing out the entities returned by {}"
- list_foo# Define a variable. Value is an expression referring to a field on the response.
- define:
variable: foo_entitiesvalue: $response.foo_entities# Print. String formatting of {} will generate code which uses idiomatic# string formatting or interpolation, e.g. ${x} in Node.js or ''.format(x) in Python.
- print:
- "Total entities returned: {}"
- foo_entities.total_count# Loop over a List collection.
- loop:
collection: foo_entities.foosvariable: foobody:
- print: ["Foo name: {}", foo.name]# Loop over a map.# Either key or value is required (or both).# If only key or value is defined for the loop, languages may generate# idiomatic code which loops over just keys or just values (versus both).
- loop:
map: foo.custom_attributeskey: attr_namevalue: attr_valuebody:
- print: ["Custom attribute {} => {}", attr_key, attr_value]# Wrap a code section in embed codes for inclusion in docs# e.g. [START foo_api_save_logs_to_disk_v1]# Note: the sample `id:` is used as an embed code which wraps the entire sample code.code_section:
id: save_logs_to_diskdescription: "Save the log files locally"body:
# Write string or bytes to local file.# Depending on if the field is a string or bytes, the generated code# will be idiomatic for saving bytes or text to a local file. define: { variable: log, value: foo.latest_log }
- write_file:
contents: log.textfile_name:
- "Foo Log {}-{}-{}"
- log.created_date.year
- log.created_date.month
- log.created_date.day
On Success
List<Statement>
Procedural list of statements representing success handling code after API request.
On Error
List<Statement> (optional)
Procedural list of statements representing error handling code after API request. If not provides, either default error handling or no error handling will be generated, depending on the language.
Return Value
Any (optional)
Value from response to return from the sample. Definition of "return" may differ between languages, this may not be a method return value in all cases.
Implementation note: templates are nothing more than structures matching those found in samples which are merged into samples.
For simplicity, samples cannot themselves be reused as template. Templates are explicitly defined as separate structures.
Selecting sections of existing samples to be used as templates hasn't worked well.
This design is simply compile-time data composition via append-only deeply merging structures.
π Defining Templates
Reusable types:
Sample Template (Full sample structure)
Common Parameter (Request message input field)
Common Statements (Response statement list)
Templates and common items are identified and used via their unique id:.
Reminder: ID configuration affects all - id: defined in the YAML document.
π Using Templates
Templates and common items are used via include:.
Include shared sample templates
sample_templates:
- id: base_samplerpc_method:
api: google.cloud.fooversion: v1service: FooServicecode_samples:
- id: list_foosinclude: [base_sample]rpc_method:
rpc: ListFoos# api: google.cloud.foo These values are merged# version: v1 into the sample via the# service: FooService template.
Include shared parameters
common_parameters:
- id: local_file_parameterinput_type: LOCAL_FILEinput_parameter: file_pathvalue: "[FILE PATH]"description: "Path to a local file"samples:
- id: list_foosrequest_config:
fields:
- field: input_config.foo_file.contentinclude: local_file_parameter# input_type: LOCAL_FILE These values are merged# input_parameter: file_path into the sample via the# value: "[FILE PATH]" template.# description: "Path to a local file"
Include shared code statements
common_statements:
- id: define_results_and_print_namescode:
- define:
variable: resultsvalue: $response.result_sets[0]
- loop:
collection: resultsvariable: resultbody:
- print: ["Name: {}", result.name]code_samples:
- id: list_fooson_success:
- print: ["Let's print out the result names:"]
- include: { id: define_results_and_print_names }# - define:# variable: results# value: $response.result_sets[0]# - loop: These values are merged# collection: results into the sample via the# variable: result template.# body:# - print: ["Name: {}", result.name]
- print: ["Done printing out result names."]
# If a template loops over items and you need to add additional code# statements into that loop, you can add statements into the `code:` block.# These statements are added into the same scope as the last statement included.
- id: list_foos_with_status_codeson_success:
- print: ["Let's print out the result names:"]
- include:
id: define_results_and_print_namescode:
# - define:# variable: results# value: $response.result_sets[0]# - loop: These values are merged# collection: results into the sample via the# variable: result template.# body:# - print: ["Name: {}", result.name]
- print: ["Result status code: {}", result.status_code]
- print: ["Done printing out result names."]
Any defined code_samples: in imported files are ignored.
When a YAML file is imported, its sample templates and common parameters/statements
become available for use in the current YAML document.
Implementation note: Imported YAML files may have their own id_config: which must be taken into
account when resolving IDs to include:. The id_config: of the YAML document being imported must not
affect the scope of the document with the imports: statement.
If an id_config: prefix or suffix is configured for the YAML document, every - id: is affected.
There is no way to define an - id:without the prefix and/or suffix being added in this case.