edit-icon download-icon

Hello World

Last Updated: Oct 15, 2018

The following samples describe how to write a hello world function in Function Compute.

In Function Compute, you can create a service, create a function for the service, and then trigger function execution. For more information, see Operations in Function Compute.

Contents

You can either use the console, the command-line tool fcli, or the SDK to create a function.

Write a function by using the console

The following example describes how to create a service, create a function, and run the function. For more information, see How to use the console.

  1. Create a service. In this example, the service is named demo. You can set the service name as needed.

    1. Configure the log project and Logstore. Log data of all functions of the service is collected to the same Logstore. For more information about logs, see Function logs.
    2. Set Role Operation to Create new role and click Authorize. A role that can access Log Service is created.
  2. Create a function.

    1. Set Trigger Type to No Trigger.
    2. Set Service Name to demo.
    3. Set Function Name. In this example, it is set to testHelloWorld. You can set the function name as needed.
    4. Select a runtime environment as needed.
      • If you select the Java runtime environment, see Java runtime environments for more information. The console does not allow you to modify Java functions online. You must package the functions into a JAR package before uploading them to the console.
    5. Skip the configuration of environment variables.
    6. Set the function handler as prompted.
    7. Set the memory size required for function execution. The default value is 512 MB and the maximum is 3072 MB. If you require a memory size larger than 3072 MB, contact us.
    8. Set the timeout period, after which the function execution forcibly stops.
    9. Skip permission configurations.
    10. Complete the function creation process.
  3. Enter the default hello world function on the code editing page of the console and click Invoke. The output and function execution log entries are displayed in the console.

In the Function Compute console, you can only view the function execution status. To view function execution logs, go to the Log Service console. For more information, see Function logs.

Create a function by using fcli

Preparations

Download the command-line tool fcli used for Function Compute, and run the fcli shell command to enter the interactive mode. For more information about fcli, see fcli.

If you are using fcli for the first time, configure the service endpoint and AccessKey as prompted. If the network does not respond during fcli downloading, click the following links to download fcli:

Write the code

Create the code folder in the current directory, and create the hello_world.js file in the code folder. A Node.js-compiled function named handler is then created. Note that you can also name the file to hello_world.py if the function is used in the Python runtime environment. The naming rules in the following examples are the same.

  1. 'use strict';
  2. module.exports.handler = function(event, context, callback) {
  3. console.log('hello world');
  4. callback(null, 'hello world');
  5. };
  1. # -*- coding: utf-8 -*-
  2. def handler(event, context):
  3. print "hello world"
  4. return 'hello world'
  1. package example;
  2. import com.aliyun.fc.runtime.Context;
  3. import com.aliyun.fc.runtime.StreamRequestHandler;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. public class HelloFC implements StreamRequestHandler {
  8. @Override
  9. public void handleRequest(
  10. InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
  11. outputStream.write(new String("hello world").getBytes());
  12. }
  13. }'
  14. // pom.xml
  15. <dependency>
  16. <groupId>com.aliyun.fc.runtime</groupId>
  17. <artifactId>fc-java-core</artifactId>
  18. <version>1.0.0</version>
  19. </dependency>

The signature of a Node.js function is function(event, context, callback). You can obtain the function output by calling a callback. For more information, see Node.js runtime environments.

The signature of a Python function is def handler(event, context). For more information, see Python runtime environments.

In the Java runtime environment, you must package the functions with the dependencies into a JAR package and then upload the package. For more information, see Java runtime environments.

Create a service

Enter the shell mode of fcli.

  1. >>> mks demo # Create a service named demo.
  2. >>> cd demo # Enter the demo service.

Create a function

  1. # In the Node.js runtime environment:
  2. >>> mkf testHelloWorld -h hello_world.handler -d code -t nodejs6
  3. # In the Python runtime environment:
  4. >>> mkf testHelloWorld -h hello_world.handler -d code -t python2.7
  5. # In the PHP runtime environment:
  6. >>> mkf testHelloWorld -h hello_world.handler -d code -t php7.2
  7. # In the Java runtime environment:
  8. >>> mkf testHelloWorld -h example.HelloFC::handleRequest -d code -t java8

Parameters

  • -h: Specifies the event processing function, that is, the handler.

    • In Python or Node.js runtime environments, a handler is in the {file}.{method} format. For example, if you set the handler argument to hello_world.handler, the handler function in the hello_world.js script file is used as the handler.
    • In the Java runtime environment, a handler is in the {package}.{class}::{method} format. For example, if the package name is example and class name is HelloFC, then the Handler specified when a function is created is example.HelloFC::handleRequest.
  • -d: Specifies the file directory. -d code: instructs fcli to use the file in the code folder of the current directory as the code file. fcli packs the code and then upload the package to Function Compute.

    • To package code, you must have installed Docker on your host. For more information about how to install Docker, see Docker installation.
    • If the image download is slow, we recommend that you use Alibaba Cloud Container Service.
    • Only root users can run Docker in the Linux operating system. Therefore, run the sudo fcli shell command to enable fcli. You can also configure the Linux host according to related documents and manage Docker as a non-root user.
    • Alternatively, you can store the code in OSS, specify the OSS path, and authorize Function Compute to access the OSS path.
  • -t: Specifies the runtime environment of a function. Currently, Node.js, Python, and Java are supported.

  • You can also use the -m parameter to specify the memory resources allocated for function execution. The default memory size is 512 MB.

  • For more information about the parameters, see mkf --help.

Run a function

  1. invk testHelloWorld

The hello world output is displayed.

View logs

  1. logs testHelloWorld

After the logs command is run, you can view all historical logs, not only the log generated in the current function execution.

Create a function by using the SDK

The code folder of the current directory contains a file named index.js. The hello world code is written in this file. You must package the code folder into a ZIP package code.zip. The following example describes how to create a function and trigger it using the SDK.For more information about SDKs in different runtime environments, see the following topics:

Python SDK sample

  1. import fc2
  2. client = fc2.Client(
  3. endpoint='<Your Endpoint>',
  4. accessKeyID='<Your AccessKeyID>',
  5. accessKeySecret='<Your AccessKeySecret>')
  6. # Create service.
  7. client.create_service('demo')
  8. # Create function.
  9. client.create_function('demo', 'testHelloWorld', 'nodejs6', 'hello_world.handler', codeDir = 'code')
  10. # Run function synchronously.
  11. client.invoke_function('demo', 'testHelloWorld')

Nodejs SDK sample

  1. 'use strict';
  2. var FCClient = require('@alicloud/fc2');
  3. var fs = require('fs');
  4. var client = new FCClient('<account id>', {
  5. accessKeyID: '<access key id>',
  6. accessKeySecret: '<access key secret>',
  7. region: 'cn-shanghai',
  8. timeout: 10000 // Request timeout in milliseconds, default is 10s
  9. });
  10. var serviceName = '<service name>';
  11. var funcName = '<function name>';
  12. client.createService(serviceName).then(function(resp) {
  13. console.log('create service: %j', resp);
  14. return client.createFunction(serviceName, {
  15. functionName: funcName,
  16. handler: 'code/index.handler',
  17. memorySize: 128,
  18. runtime: 'nodejs6',
  19. code: {
  20. zipFile: fs.readFileSync('/tmp/code.zip', 'base64'),
  21. },
  22. });
  23. }).then(function(resp) {
  24. console.log('create function: %j', resp);
  25. return client.invokeFunction(serviceName, funcName);
  26. }).then(function(resp) {
  27. console.log('invoke function: %j', resp);
  28. }).catch(function(err) {
  29. console.error(err);
  30. });

Java SDK sample

  1. import com.aliyuncs.fc.client.FunctionComputeClient;
  2. import com.aliyuncs.fc.model.Code;
  3. import com.aliyuncs.fc.request.*;
  4. import com.aliyuncs.fc.response.*;
  5. import java.io.IOException;
  6. public class testJavaSDK {
  7. private static final String CODE_DIR = "../code";
  8. private static final String REGION = "cn-shanghai";
  9. private static final String SERVICE_NAME = "demo";
  10. private static final String FUNCTION_NAME = "testHelloWorld";
  11. public static void main(final String[] args) throws IOException {
  12. String accountId = "<account id>";
  13. String accessKey = "<access key id>";
  14. String accessSecretKey = "<access key secret>";
  15. // Initialize FC client
  16. FunctionComputeClient fcClient = new FunctionComputeClient(REGION, accountId, accessKey, accessSecretKey);
  17. // Set to a specific endpoint in case needed, endpoint sample: http://123456.cn-hangzhou.fc.aliyuncs.com
  18. // fcClient.setEndpoint("http://{accountId}.{regionId}.fc.aliyuncs.com.");
  19. // Create a service
  20. CreateServiceRequest csReq = new CreateServiceRequest();
  21. csReq.setServiceName(SERVICE_NAME);
  22. csReq.setDescription("FC test service");
  23. CreateServiceResponse csResp = fcClient.createService(csReq);
  24. System.out.println("Created service, request ID " + csResp.getRequestId());
  25. // Create a function
  26. CreateFunctionRequest cfReq = new CreateFunctionRequest(SERVICE_NAME);
  27. cfReq.setFunctionName(FUNCTION_NAME);
  28. cfReq.setDescription("Function for test");
  29. cfReq.setMemorySize(128);
  30. cfReq.setHandler("index.handler");
  31. cfReq.setRuntime("nodejs6");
  32. Code code = new Code().setDir(CODE_DIR);
  33. cfReq.setCode(code);
  34. cfReq.setTimeout(10);
  35. CreateFunctionResponse cfResp = fcClient.createFunction(cfReq);
  36. System.out.println("Created function, request ID " + cfResp.getRequestId());
  37. // Run the function with a string as function event parameter, Sync mode
  38. InvokeFunctionRequest invkReq = new InvokeFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
  39. InvokeFunctionResponse invkResp = fcClient.invokeFunction(invkReq);
  40. System.out.println(new String(invkResp.getContent()));
  41. }
  42. }
  43. // pom.xml
  44. <?xml version="1.0" encoding="UTF-8"?>
  45. <project xmlns="http://maven.apache.org/POM/4.0.0"
  46. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  47. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  48. <modelVersion>4.0.0</modelVersion>
  49. <groupId>testSDK</groupId>
  50. <artifactId>testSDK</artifactId>
  51. <version>1.0-SNAPSHOT</version>
  52. <dependencies>
  53. <dependency>
  54. <groupId>com.aliyun</groupId>
  55. <artifactId>aliyun-java-sdk-fc</artifactId>
  56. <version>1.1.8</version>
  57. </dependency>
  58. </dependencies>
  59. </project>
Thank you! We've received your feedback.