Invoking a function in Cloud Functions
You can invoke a function:
Each method has its own data structure for function requests and responses. You can invoke a specific function version using a tag. Learn more about how to invoke a function.
Invoking a function using HTTPS
If a function is invoked for processing an HTTPS request, it gets the request data in JSON format in the first argument: the HTTP method name, headers, arguments, and other request parameters.
The result returned by the function should also be a JSON document. It should contain the HTTP response code, response headers, and response content. Cloud Functions automatically processes this JSON document and returns data in a standard HTTPS response to the user.
Note
You can run functions by specifying the ?integration=raw
request string parameter. When invoked this way, a function cannot parse or set HTTP headers:
- The contents of the HTTPS request body are provided as the first argument (without converting to a JSON structure).
- The contents of the HTTPS response body is identical to the function response (without converting or checking the structure) and the HTTP response status is 200.
Request structure
JSON query structure:
{
"httpMethod": "<HTTP method name>",
"headers": <dictionary with HTTP header string values>,
"multiValueHeaders": <dictionary with lists of HTTP header values>,
"queryStringParameters": <dictionary of queryString parameters>,
"multiValueQueryStringParameters": <dictionary with lists of queryString parameter values>,
"requestContext": <dictionary with request context>,
"body": "<request contents>",
"isBase64Encoded": <true or false>
}
Where:
-
httpMethod
: HTTP method name, such as DELETE, GET, HEAD, OPTIONS, PATCH, POST, or PUT. -
headers
: Dictionary of strings with HTTP request headers and their values. If the same header is provided multiple times, the dictionary contains the last provided value. -
multiValueHeaders
: Dictionary with HTTP request headers and lists of their values. It contains the same keys as theheaders
dictionary, but if any header is repeated multiple times, its list contains all the provided values for this header. If the header is provided only once, it is included in this dictionary and the list for it will contain a single value. -
queryStringParameters
: Dictionary with query parameters. If the same parameter is set multiple times, the dictionary contains the last specified value. -
multiValueQueryStringParameters
: Dictionary with a list of all specified values for each query parameter. If the same parameter is set multiple times, the dictionary contains all the specified values. -
requestContext
contains the following structure:{ "identity": "<collection of key:value pairs for user authentication>", "httpMethod": "<DELETE, GET, HEAD, OPTIONS, PATCH, POST, or PUT>", "requestId": "<request ID, router-generated>", "requestTime": "<request time in CLF format>", "requestTimeEpoch": "<request time in Unix format>", "authorizer": "<dictionary with authorization context>", "apiGateway": "<dictionary of custom data transmitted by API gateway for function call>", "connectionId": "<web socket connection ID>", "connectedAt": "<web socket connection time>", "eventType": "<web socket event or operation type: CONNECT, MESSAGE, DISCONNECT>", "messageId": "<ID of message received from web socket>", "disconnectStatusCode": "<web socket closure status code>", "disconnectReason": "<web socket disconnection cause description in text format>" }
Structure of the
identity
element:{ "sourceIp": "<request source address>", "userAgent": "<contents of the original request User-Agent HTTP header>" }
apiGateway
element structure:{ "operationContext": "<dictionary with operation context described in API gateway spec>" }
authorizer
element structure:{ "jwt": { // Field that is filled in by the API Gateway JWT authorizer. Contains data about the user and their permissions' "claims": "<dictionary of JWT body fields>", "scopes": "<list of JWT owner permissions>" } // Other authorization context fields returned from the authorizer function }
-
body
: Request body in string format. Data can be Base64-encoded (in this case, Cloud Functions setsisBase64Encoded: true
).Note
If the function is invoked with the
Content-Type: application/json
header, the contents ofbody
remains in the original format (isBase64Encoded: false
). -
isBase64Encoded
: Ifbody
contains Base64-encoded data, then Cloud Functions sets the parameter totrue
.
Debugging functions
To debug parameter processing, use a function that returns the JSON structure of the request. An example of such function is given below.
module.exports.handler = async (event) => {
return {
body: JSON.stringify(event)
};
};
For example, for the request:
curl -XPOST -d "hello, world!" "https://functions.yandexcloud.net/<function ID>?a=1&a=2&b=1"
The result looks like this:
{
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Content-Length": "13",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "curl/7.58.0",
"X-Real-Remote-Address": "[88.99.0.24]:37310",
"X-Request-Id": "cd0d12cd-c5f1-4348-9dff-c50a78f1eb79",
"X-Trace-Id": "92c5ad34-54f7-41df-a368-d4361bf376eb"
},
"path": "",
"multiValueHeaders": {
"Accept": [ "*/*" ],
"Content-Length": [ "13" ],
"Content-Type": [ "application/x-www-form-urlencoded" ],
"User-Agent": [ "curl/7.58.0" ],
"X-Real-Remote-Address": [ "[88.99.0.24]:37310" ],
"X-Request-Id": [ "cd0d12cd-c5f1-4348-9dff-c50a78f1eb79" ],
"X-Trace-Id": [ "92c5ad34-54f7-41df-a368-d4361bf376eb" ]
},
"queryStringParameters": {
"a": "2",
"b": "1"
},
"multiValueQueryStringParameters": {
"a": [ "1", "2" ],
"b": [ "1" ]
},
"requestContext": {
"identity": {
"sourceIp": "88.99.0.24",
"userAgent": "curl/7.58.0"
},
"httpMethod": "POST",
"requestId": "cd0d12cd-c5f1-4348-9dff-c50a78f1eb79",
"requestTime": "26/Dec/2019:14:22:07 +0000",
"requestTimeEpoch": 1577370127
},
"body": "aGVsbG8sIHdvcmxkIQ==",
"isBase64Encoded": true
}
Service data
Optionally, the function can accept the second argument with the following structure:
{
"requestId": "<request ID>",
"functionName": "<function ID>",
"functionVersion": "<function version ID>",
"memoryLimitInMB": "<amount of memory available to function version, MB>",
"token": "<IAM token, optional>",
}
Where:
requestId
: ID of the function call, generated when the function is accessed and displayed in the function call log.functionName
: Function ID.functionVersion
: ID of the function version.memoryLimitInMB
: Amount of memory given for the function version, in MB.token
: IAM token of the service account specified for the function version. The current value is generated automatically. It is used for working with the Yandex Cloud API. This field is present only if the correct service account is specified for the function version.
Example of using service data in a function:
module.exports.handler = async (event, context) => {
const iamToken = context.token;
...
return {
body: ...
};
};
Response structure
Cloud Functions interprets the function execution result to fill in the HTTPS response contents, headers, and status code. For this to work, the function must return a response in the following structure:
{
"statusCode": <HTTP response code>,
"headers": <dictionary with HTTP header string values>,
"multiValueHeaders": <dictionary with lists of HTTP header values>,
"body": "<response contents>",
"isBase64Encoded": <true or false>
}
Where:
statusCode
: HTTP status code, which the client uses to interpret the request results.headers
: Dictionary of strings with HTTP response headers and their values.multiValueHeaders
: Dictionary listing one or more HTTP response headers. If the same header is specified in both theheaders
andmultiValueHeaders
dictionaries, the contents of theheaders
dictionary is ignored.body
: Response body in string format. To work with binary data, the contents can be Base64-encoded. In this case, setisBase64Encoded: true
.isBase64Encoded
: Ifbody
is Base64-encoded, set the parameter totrue
.
Handling errors in user-defined function code
If an unhandled error occurs in user code, Cloud Functions returns a 502 error and error details in the following JSON structure:
{
"errorMessage": "<error message>",
"errorType": "<error type>",
"stackTrace": <list of invoked methods, optional>
}
Where:
errorMessage
: String with an error description.errorType
: Programming language-dependent type of error or exception.stackTrace
: Function execution stack at the time of the error.
The specific contents of these fields depend on the programming language and your function's runtime environment.
Error in the event the response has an invalid JSON structure
If the response structure of your function does not match the description given in Response data structure, Cloud Functions returns the result with a 502 error code and the following response:
{
"errorMessage": "Malformed serverless function response: not a valid json",
"errorType": "ProxyIntegrationError",
"payload": "<original contents of the function response>"
}
Possible Cloud Functions response codes
If the error occurs in a user-defined function, the X-Function-Error: true
header is added to the response.
Cloud Functions can return results with the following HTTP codes:
200 OK
: Successful function execution.400 BadRequest
: Error in HTTPS request parameters.403 Forbidden
: Can't execute the request due to restrictions on client access to the function.404 Not Found
: The function is not found at the specified URL.413 Payload Too Large
: The limit for the request JSON structure is exceeded by more than 3.5 MB.429 TooManyRequests
: The function call intensity is too high:- The quota on the number of requests executed is exceeded.
- Can't execute this request because all executors are already overloaded by the existing requests to this function.
500 Internal Server Error
: Internal server error.502 BadGateway
: Incorrect function code or format of the returning JSON response.503 Service Unavailable
: Cloud Functions is unavailable.504 Gateway Timeout
: Exceeded maximum function execution time before timeout.
Filtering message headers
Your function receives and transmits the contents of HTTP headers as JSON fields (see the description above). Some request and response headers are removed or renamed as described below.
Removed from a request:
- "Expect"
- "Te"
- "Trailer"
- "Upgrade"
- "Proxy-Authenticate"
- "Authorization"
- "Connection"
- "Content-Md5"
- "Max-Forwards"
- "Server"
- "Transfer-Encoding"
- "Www-Authenticate"
- "Cookie"
-
Removed from a response:
- "Host"
- "Authorization"
- "User-Agent"
- "Connection"
- "Max-Forwards"
- "Cookie"
- "X-Request-Id"
- "X-Function-Id"
- "X-Function-Version-Id"
- "X-Content-Type-Options"
-
Cause an error if present in a response:
- "Proxy-Authenticate"
- "Transfer-Encoding"
- "Via"
-
Overwritten by adding the
X-Yf-Remapped-
prefix:- "Content-Md5"
- "Date"
- "Server"
- "Www-Authenticate"
IP address of the request source
If a request contains the X-Forwarded-For
Invoking a function using the Yandex Cloud CLI
Function calls from the CLI are HTTPS requests using the POST method and the ?integration=raw
parameter (without converting the request to a JSON structure or checking the response).
View the help for the function call command:
yc serverless function invoke --help
Invoke the specified function
Usage:
yc serverless function invoke <FUNCTION-NAME>|<FUNCTION-ID> [Flags...] [Global Flags...]
Flags:
--id string Function id.
--name string Function name.
--tag string Tag. Default $latest.
-d, --data string Data to be sent
--data-file string Data (file location) to be sent
--data-stdin Await stdin for data to be sent
Detailed description of how to transfer data using different flags and arguments:
-
If a flag or argument is omitted, an empty string is provided.
-
-d, --data
: Data is provided as an argument.yc serverless function invoke <function ID> -d '{"queryStringParameters": {"parameter_name": "parameter_value"}}'
-
--data-file
: Data is read from a file.yc serverless function invoke <function ID> --data-file <file path>
Similar to the command with the
-d
argument with the@<file_name>
value:yc serverless function invoke <function_ID> -d @<file_path>
-
--data-stdin
: Data is read from the input stream.echo '{"queryStringParameters": {"parameter_name": "parameter_value"}}' | yc serverless function invoke <function ID> --data-stdin
Similar to a command with the
-d
argument set to@-
:echo '{"queryStringParameters": {"parameter_name": "parameter_value"}}' | yc serverless function invoke <function ID> -d @-`.
Invoking a function using a trigger
When invoking a function using a trigger, the JSON description of a trigger event is provided in the body of an HTTP request to the function. The request source IP is provided in the same way as when invoking a function using HTTPS. Learn more about triggers.
Invoking a function using a Yandex API Gateway extension
When invoking a function using the API Gateway extension, the function receives an HTTP request addressed to the API gateway. In this case, the Host
header specifies the host on which the user accessed the API gateway rather than the function's host. The request source IP is provided in the same way as when invoking a function using HTTPS. Learn more about the extension in the Yandex API Gateway documentation.