関数を作成したら、新しく作成した関数を入力し、選択したプログラミング言語に従って、サンプルコードをコンソールのコードエディタに貼り付けます。
Node.js
Node.js を使用する場合は、コードエディタで関数を直接記述できます。
module.exports.handler = function(event, context, callback) {
var event = JSON.parse(event);
var content = {
path: event.path,
method: event.method,
headers: event.headers,
queryParameters: event.queryParameters,
pathParameters: event.pathParameters,
body: event.body
// you can deal with your own logic here.
}
var response = {
isBase64Encoded: false,
statusCode: '200',
headers: {
'x-custom-header': 'header value'
},
body: content
};
callback(null, response)
};
Python
Python を使用する場合は、コードエディタで関数を直接記述できます。
# -*- coding: utf-8 -*-
import json
def handler(event, context):
event = json.loads(event)
content = {
'path': event['path'],
'method': event['httpMethod'],
'headers': event['headers'],
'queryParameters': event['queryParameters'],
'pathParameters': event['pathParameters'],
'body': event['body']
}
# you can deal with your own logic here.
rep = {
"isBase64Encoded": "false",
"statusCode": "200",
"headers": {
"x-custom-header": "no"
},
"body": content
}
return json.dumps(rep)
Java
Java を使用する場合は、コードと依存関係を jar ファイルに結合し、ファイルを Function Compute にアップロードする必要があります。Function Compute の Java ランタイム環境については、「Java」をご参照ください。
Java でプログラミングする場合は、Function Compute の定義済みメソッドを使用するクラスを実装する必要があります。事前定義された 2 つのメソッドが使用できます。
(推奨) PojoRequestHandler<I, O>
メソッドの使用
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;
import java.util.HashMap;
import java.util.Map;
public class ApiTriggerDemo implements PojoRequestHandler<ApiRequest, ApiResponse> {
public ApiResponse handleRequest(ApiRequest request, Context context) {
// Get ApiRequest info
context.getLogger().info(request.toString());
String path = request.getPath();
String httpMethod = request.getHttpMethod();
String body = request.getBody();
context.getLogger().info("path:" + path);
context.getLogger().info("httpMethod:" + httpMethod);
context.getLogger().info("body:" + body);
// Deal with your own logic here
// ApiResponse example
Map headers = new HashMap();
boolean isBase64Encoded = false;
int statusCode = 200;
String returnBody = "";
return new ApiResponse(headers,isBase64Encoded,statusCode,returnBody);
}
}
2 つの pojo
クラス、ApiRequest
クラスと ApiResponse
クラスは、以下の通りです。注意: pojo
クラスの set()
とget()
メソッドをすべて記述してください。
import java.util.Map;
public class ApiRequest {
private String path;
private String httpMethod;
private Map headers;
private Map queryParameters;
private Map pathParameters;
private String body;
private boolean isBase64Encoded;
@Override
public String toString() {
return "Request{" +
"path='" + path + '\'' +
", httpMethod='" + httpMethod + '\'' +
", headers=" + headers +
", queryParameters=" + queryParameters +
", pathParameters=" + pathParameters +
", body='" + body + '\'' +
", isBase64Encoded=" + isBase64Encoded +
'}';
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public Map getHeaders() {
return headers;
}
public void setHeaders(Map headers) {
this.headers = headers;
}
public Map getQueryParameters() {
return queryParameters;
}
public void setQueryParameters(Map queryParameters) {
this.queryParameters = queryParameters;
}
public Map getPathParameters() {
return pathParameters;
}
public void setPathParameters(Map pathParameters) {
this.pathParameters = pathParameters;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public boolean getIsBase64Encoded() {
return this.isBase64Encoded;
}
public void setIsBase64Encoded(boolean base64Encoded) {
this.isBase64Encoded = base64Encoded;
}
}
import java.util.Map;
public class ApiResponse {
private Map headers;
private boolean isBase64Encoded;
private int statusCode;
private String body;
public ApiResponse(Map headers, boolean isBase64Encoded, int statusCode, String body) {
this.headers = headers;
this.isBase64Encoded = isBase64Encoded;
this.statusCode = statusCode;
this.body = body;
}
public Map getHeaders() {
return headers;
}
public void setHeaders(Map headers) {
this.headers = headers;
}
public boolean getIsBase64Encoded() {
return isBase64Encoded;
}
public void setIsBase64Encoded(boolean base64Encoded) {
this.isBase64Encoded = base64Encoded;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
pom.xml
ファイルは次のとおりです。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>apiTrigger</groupId>
<artifactId>apiTrigger</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.aliyun.fc.runtime</groupId>
<artifactId>fc-java-core</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
StreamRequestHandler
メソッドの使用
次の例では、 StreamRequestHandler
メソッドの使用について説明します。入力 InputStream
は、対応する POJO クラスに変換する必要があります。pom.xml
ファイルは、PojoRequestHandler<I, O>
メソッドと同じように構成されています。
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.fc.runtime.Context;
import com.google.gson.Gson;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class ApiTriggerDemo2 implements StreamRequestHandler {
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) {
try {
// Convert InputStream to string
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String string = "";
while ((string = bufferedReader.readLine()) != null) {
stringBuffer.append(string);
}
String input = stringBuffer.toString();
context.getLogger().info("inputStream: " + input);
Request req = new Gson().fromJson(input, Request.class);
context.getLogger().info("input req: ");
context.getLogger().info(req.toString());
String bodyReq = req.getBody();
Base64.Decoder decoder = Base64.getDecoder();
context.getLogger().info("body: " + new String(decoder.decode(bodyReq)));
// Deal with your own logic here
// construct response
Map headers = new HashMap();
headers.put("x-custom-header", " ");
boolean isBase64Encoded = false;
int statusCode = 200;
Map body = new HashMap();
Response resp = new Response(headers, isBase64Encoded, statusCode, body);
String respJson = new Gson().toJson(resp);
context.getLogger().info("outputStream: " + respJson);
outputStream.write(respJson.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Request {
private String path;
private String httpMethod;
private Map headers;
private Map queryParameters;
private Map pathParameters;
private String body;
private boolean isBase64Encoded;
@Override
public String toString() {
return "Request{" +
"path='" + path + '\'' +
", httpMethod='" + httpMethod + '\'' +
", headers=" + headers +
", queryParameters=" + queryParameters +
", pathParameters=" + pathParameters +
", body='" + body + '\'' +
", isBase64Encoded=" + isBase64Encoded +
'}';
}
public String getBody() {
return body;
}
}
// FC need to return the response to API Gateway in the following JSON format
class Response {
private Map headers;
private boolean isBase64Encoded;
private int statusCode;
private Map body;
public Response(Map headers, boolean isBase64Encoded, int statusCode, Map body) {
this.headers = headers;
this.isBase64Encoded = isBase64Encoded;
this.statusCode = statusCode;
this.body = body;
}
}
}