After you create an HTTP trigger, you can start writing the code of the function. This topic describes how to write a function in the Function Compute console.

Prerequisites

Create a trigger

Procedure

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Service/Function.
  4. Find the required function in the required service and click the name of the function.
    requiredfunction
  5. Click the Code tab and write code in the code editor.
    The sample code is as follows:
    var getRawBody = require('raw-body')
    module.exports.handler = function (request, response, context) {
        // get request info
        getRawBody(request, function (err, data) {
            var params = {
                path: request.path,
                queries: request.queries,
                headers: request.headers,
                method: request.method,
                body: data,
                url: request.url,
                clientIP: request.clientIP,
            }
            // you can deal with your own logic here
            // set response
            var respBody = new Buffer.from(JSON.stringify(params));
            // var respBody = new Buffer( )
            response.setStatusCode(200)
            response.setHeader('content-type', 'application/json')
            response.send(respBody)
        })
    };
    # -*- coding: utf-8 -*-
    import json
    HELLO_WORLD = b"Hello world!\n"
    def handler(environ, start_response):
        request_uri = environ['fc.request_uri']
        response_body = {
          'uri':environ['fc.request_uri'],
          'method':environ['REQUEST_METHOD']
        }
        # do something here
        status = '200 OK'
        response_headers = [('Content-type', 'text/json')]
        start_response(status, response_headers)
        # Python2
        return [json.dumps(response_body)]
        # Python3 tips: When using Python3, the str and bytes types cannot be mixed.
        # Use str.encode() to go from str to bytes
        # return [json.dumps(response_body).encode()]
    <?php
    use RingCentral\Psr7\Response;
    function handler($request, $context): Response{
        /*
        $body       = $request->getBody()->getContents();
        $queries    = $request->getQueryParams();
        $method     = $request->getMethod();
        $headers    = $request->getHeaders();
        $path       = $request->getAttribute("path");
        $requestURI = $request->getAttribute("requestURI");
        $clientIP   = $request->getAttribute("clientIP");
        */
        return new Response(
            200,
            array(
                "custom_header1" => "v1",
                "custom_header2" => ["v2", "v3"],
            ),
            "hello world"
        );
    }

What to do next

Test a function