Web action
    • PDF

    Web action

    • PDF

    Article Summary

    Available in Classic

    You can set up web actions in the NAVER Cloud Platform console's Cloud Functions > Action. Web actions are Cloud Functions actions that allow you to provide web services. You can use web actions to write simple code and release webpages, data, etc., on the internet in formats such as HTTP, HTML, SVG, JSON, TXT, etc.
    You can implement your own authentication logic in the action code if a separate authentication logic is required, or add an API key or IAM authentication setting to the external link URL connected to the web action, using NAVER Cloud Platform's API Gateway.
    Refer to Running action or trigger and Action for how to run and monitor actions that have been created.

    Web action settings

    You can set web property to True for all types (basic, sequence) of actions. The following describes how to set up web action when creating an action.

    1. Create an action with the web property.
      function main({name}) {
        var msg = 'you did not tell me who you are.';
        if (name) {
          msg = `hello ${name}!`
        }
        return {body: `<html><body><h3>${msg}</h3></body></html>`}
      }
      
    2. Set up an external link address.
    3. Call and view the result.
      • Request format
      $ curl
      --header "Content-Type: application/json" \
      --data '{"name":"cloud functions"}' \
      --request POST https://{product_id}.apigw.ntruss.com/{api_name}/{stage_name}/{resource_name}/http
      
      • Response format
      <html><body><h3>hello cloud functions!</h3></body></html>
      

    HTTP request handling

    Web actions can be used to implement HTTP handlers that respond with diverse content such as headers, statusCode, body, etc.
    A web action must return a JSON object in the same way as a regular action, but the Cloud Functions system controller treats a web action differently if the JSON object's top-level properties contain one or more of the following.

    • headers: This is a JSON object where the keys are header names and the values are string, number, or Boolean values. To send multiple values to a single header, the header’s value must be a JSON array of values.
    • statusCode: This is a valid HTTP status code. 204 No Content is returned if the body is empty (default: 200 OK).
    • body: regular text, JSON object, array string, binary data encoded in Base64 (default: empty response)
    Note

    If the body is null, empty string (""), or undefined, then it is considered to have no content.

    Cloud Functions system controller delivers headers specified by an action to the HTTP client when a request or response is finished. The HTTP client responds by the status code given. The body is delivered as the response's body. If a content-type header is not defined in headers in the response, then the body is interpreted as application/json in cases when the body is not a string, and as text/html in all other cases.
    If content-type is defined and he response is binary data or plain text, then the Cloud Functions controller decodes the string by using the Base64 decoder as needed. If the body is not decoded correctly, then it's determined as an error.

    Raw HTTP handling

    Cloud Functions Judges between the binary and plain text content type using the Akka HTTP framework, which allows Cloud Functions's web actions to efficiently interpret and handle HTTP sources. For example, the params.__ow_method value can be used in the code to see which HTTP method was used when a request was made. The following shows the example code and execution result you can refer to.

    • Example code
      function main(params) {
              return params
      }
      
    • Execution result
      $ curl https://{Action_URL}/json?key=value -X POST -H "Content-Type: application/json" -d '{"key":"value"}'
      {
        "response": {
          "__ow_method": "post",
          "__ow_body": "",
          "__ow_headers": {
            "accept": "*/*",
            "connection": "close",
            "content-length": "15",
            "content-type": "application/json",
            "host": "172.17.0.1",
            "user-agent": "curl/7.43.0"
          },
          "__ow_path": "",
          "key": "value"
        }
      }
      

    Base64-type binary decoding

    If the content-type is binary when handling raw HTTP content, then it's probable that the __ow_body content is encoded in Base64. You can see how bodies encoded in various runtime environments are handled through the following example code.

    • Node.js
      function main(args) {
          decoded = new Buffer(args.__ow_body, 'base64').toString('utf-8')
          return {body: decoded}
      }
      
    • Python
      def main(args):
          try:
              decoded = args['__ow_body'].decode('base64').strip()
              return {"body": decoded}
          except:
              return {"body": "Could not decode body from Base64."}
      
    • Swift
      extension String {
          func base64Decode() -> String? {
              guard let data = Data(base64Encoded: self) else {
                  return nil
              }
      
              return String(data: data, encoding: .utf8)
          }
      }
      
      func main(args: [String:Any]) -> [String:Any] {
          if let body = args["__ow_body"] as? String {
              if let decoded = body.base64Decode() {
                  return [ "body" : decoded ]
              }
          }
      
          return ["body": "Could not decode body from Base64."]
      }
      

    You can test actual web tasks by saving the functions in the example code above and creating raw HTTP web actions. The following is an example of the result of running a command after saving a Node.js function with the decode action.

    $ curl -k -H "Content-Type: text/plain" -X POST -d "RGVjb2RlZCBib2R5" https://{Action_URL}/json
    
    {
      "body": "Decoded body"
    }
    

    OPTIONS request

    By default, an OPTIONS request results in CORS headers being automatically added to the response header. These headers allow all origins, as well as OPTIONS, GET, DELETE, POST, PUT, HEAD, and PATCH methods. If there is an additional HTTP request, then the Access-Control-Request-Headers header will echo back as the Access-Control-Allow-Headers header. The following is the default value created.

    Access-Control-Allow-Origin: *
    Access-Control-Allow-Methods: OPTIONS, GET, DELETE, POST, PUT, HEAD, PATCH
    Access-Control-Allow-Headers: Authorization, Content-Type
    

    OPTIONS requests can also be handled manually by a web action. For this, the web-custom-options option must be enabled by setting it to true. When this option is enabled, CORS headers are no longer added automatically. The user must program the code to determine and add the headers themselves. The following is example code where the user manually responds to an OPTIONS request.

    function main(params) {
      if (params.__ow_method == "options") {
        return {
          headers: {
            'Access-Control-Allow-Methods': 'OPTIONS, GET',
            'Access-Control-Allow-Origin': 'example.com'
          },
          statusCode: 200
        }
      }
    }
    

    The following is an example of the result of running a command after saving the function above.

    $ curl https://{Action_URL}/http -kvX OPTIONS
    < HTTP/1.1 200 OK
    < Server: nginx/1.11.13
    < Content-Length: 0
    < Connection: keep-alive
    < Access-Control-Allow-Methods: OPTIONS, GET
    < Access-Control-Allow-Origin: example.com
    

    Additional features

    The additional features provided by web actions are as follows.

    Content extensions

    This specifies the desired content type as /json, /html, /http, /svg, or /text. It is run by adding an extension to the URI's action name, and an /{web_action_url} action is used as /{web_action_url}/http to receive an HTTP response.

    Caution

    An action will not be executed if the content type is not specified.

    Query and body parameters as input

    An action receives query parameters as well as parameters in the request body. The order of priority for merging parameters is package parameters, action parameters, and query parameter. The previous value of each is redefined in order if there is an overlap. For instance, a request such as /{Web_Action_URL}/http/?name=Jane delivers {name: "Jane"} as an input parameter to the action.

    Form data

    An web action can receive URL-encoded form data application/x-www-form-urlencoded data as an input as well as standard application/json.

    Activation via multiple HTTP verbs

    A web action can be executed through an HTTP method (GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS).

    Non JSON body and raw HTTP entity handling

    A web action can handle HTTP request bodies other than JSON objects, and you can set it to always have accept values delivered that are difficult to understand (plain text when not binary, or Base64-encoded strings).

    Error handling

    A web action failure is processed in one of the following two failure modes.

    • Application error: Returns the top-priority JSON object that has an action with the error property. It's similar to a catch exception.
    • Developer error: It occurs when the action fails and does not produce a response. It is similar to an uncaught exception.

    An application error needs to be specified and handled by the user, which is why we recommend that you create error messages for each web action content type. For instance, you can create an error message where web actions used with the .http extension must return an HTTP response such as {error: { statusCode: 400 }, so that the content-type of the extension and content-type of the error response action are aligned.


    Was this article helpful?

    What's Next
    Changing your password will log you out immediately. Use the new password to log back in.
    First name must have atleast 2 characters. Numbers and special characters are not allowed.
    Last name must have atleast 1 characters. Numbers and special characters are not allowed.
    Enter a valid email
    Enter a valid password
    Your profile has been successfully updated.