Updated on 2023-11-15 GMT+08:00

Building a Program

Creating an API group

Before creating a function and adding an event source, create an API group to store and manage APIs.

Before enabling APIG functions, buy a gateway by referring to Buying a Gateway.

  1. Log in to the APIG console, choose API Management > API Groups in the navigation pane, and click Create API Group in the upper right.
  2. Select Create Directly, set the group information, and click OK.

    • Name: Enter a group name, for example, APIGroup_test.
    • Description: Enter a description about the group.

Creating a Custom Authentication Function

Frontend custom authentication means APIG uses a function to authenticate received API requests. To authenticate API requests by using your own system, create a frontend custom authorizer in APIG. Create a FunctionGraph function with the required authentication information. Then use it to authenticate APIs in APIG.

This section uses the header parameter event["headers"] as an example. For the description about request parameters, see Request Parameter Code Example.

  1. In the left navigation pane of the management console, choose Compute > FunctionGraph to go to the FunctionGraph console. Then choose Functions > Function List in the navigation pane.
  2. Click Create Function.
  3. Set the function information, and click Create Function.

    • Template: Select Create from scratch.
    • Function Name: Enter a function name, for example, apig-test.
    • Agency: Select Use no agency.
    • Runtime: Select Python 2.7.

  4. On the function details page that is displayed, click the Code tab and copy the example request parameter code to the online editor, and click Deploy.
  5. Click Configure Test Event, and select apig-event-template. Modify the template as required, and click Create. In this example, add "auth":"abc" to "headers".

    Figure 1 Configuring a test event

  6. Click Test. If the result is Execution successful, the function is successfully created.

    Figure 2 Viewing the execution result

Creating a Custom Authorizer

Create a custom authorizer in APIG and connect it to the frontend custom authentication function.

  1. In the left navigation pane of the management console, choose Middleware > API Gateway to go to the APIG console. In the navigation pane, choose API Management > API Policies. On the Custom Authorizers tab, click Create Custom Authorizer.
  2. Configure basic information about the custom authorizer according to the following figure.

    • Name: Enter a name, for example, Authorizer_test.
    • Type: Select Frontend.
    • Function URN: Select apig-test.
      Figure 3 Creating a custom authorizer

  3. Click OK.

Creating a Backend Service Function

APIG supports FunctionGraph backends. After you create a FunctionGraph backend API, APIG will trigger the relevant function, and the function execution result will be returned to APIG.

  1. Create a service function by referring to Creating a Custom Authentication Function. The function name must be unique.
  2. On the Code tab of the function details page, copy the following code to the online editor, and click Deploy.

    # -*- coding:utf-8 -*-
    import json
    def handler (event, context):
        body = "<html><title>Functiongraph Demo</title><body><p>Hello, FunctionGraph!</p></body></html>"
        print(body)
        return {
            "statusCode":200,
            "body":body,
            "headers": {
                "Content-Type": "text/html",
            },        
            "isBase64Encoded": False
        }

Request Parameter Code Example

The following are the requirements you must meet when developing FunctionGraph functions. Python 2.7 is used as an example.

The function must have a clear API definition. Example:

def handler (event, context)
  • handler: name of the entry point function. The name must be consistent with that you define when creating a function.
  • event: event parameter defined in JSON format for the function.
  • context: runtime information provided for executing the function. For details, see SDK APIs.
event supports three types of request parameters in the following formats:
  • Header parameter: event["headers"]["Parameter name"]
  • Query string: event["queryStringParameters"]["Parameter name"]
  • Custom user data: event["user_data"]
The three types of request parameters obtained by the function are mapped to the custom authentication parameters defined in APIG.
  • Header parameter: Corresponds to the identity source specified in Header for custom authentication. The parameter value is transferred when the API that uses custom authentication is called.
  • Query string: Corresponds to the identity source specified in Query for custom authentication. The parameter value is transferred when the API that uses custom authentication is called.
  • Custom user data: Corresponds to the user data for custom authentication. The parameter value is specified when the custom authorizer is created.
  • The function response cannot be greater than 1 MB and must be in the following format:
    {     "statusCode":200,
          "body": "{\"status\": \"allow\", \"context\": {\"user\": \"abc\"}}" 
     }

The body field is a character string, which is JSON-decoded as follows:

{
	"status": "allow/deny",
	"context": {
		"user": "abc"
	}
}

The status field is mandatory and is used to identify the authentication result. The authentication result can only be allow or deny. allow indicates that the authentication is successful, and deny indicates that the authentication fails.

The context field is optional and can only be key-value pairs. The key value cannot be a JSON object or an array.

The context field contains custom user data. After successful authentication, the user data is mapped to the backend parameters. The parameter name in context is case-sensitive and must be the same as the system parameter name. The parameter name must start with a letter and can contain 1 to 32 characters, including letters, digits, hyphens (-), and underscores (_).

Example Header Parameter

# -*- coding:utf-8 -*-
import json
def handler(event, context):
    if event["headers"].get("auth")=='abc':
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user":"success"
                }
            })
        }
    else:
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"deny",
            })   
        }
    return json.dumps(resp)

Example Query String

# -*- coding:utf-8 -*-
import json
def handler(event, context):
    if event["queryStringParameters"].get("test")=='abc':
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user":"abcd"
                }
            })
        }
    else:
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"deny",
            })   
        }
    return json.dumps(resp)

Example User Data

# -*- coding:utf-8 -*-
import json
def handler(event, context):
    if event.get("user_data")=='abc':
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"allow",
                "context":{
                    "user":"abcd"
                }
            })
        }
    else:
        resp = {
            'statusCode': 200,
            'body': json.dumps({
                "status":"deny",
            })   
        }
    return json.dumps(resp)