You can find many more advanced examples and real-life use cases using Serverless products in our Serverless Examples repository.
Code examples for Serverless Functions
This page shows examples of functions in Python, Node, Golang, PHP, and Rust that can be used in your Serverless Functions projects.
Before you start
To complete the actions presented below, you must have:
- A Scaleway account logged into the console
- Owner status or IAM permissions allowing you to perform actions in the intended Organization
- A Serverless Functions namespace
- A text editor/IDE (such as
vi
or Visual Studio Code) - Knowledge of how to package your functions and their dependencies
Python
Returning a function result in Python
There are several ways to return a response from a handler function:
Response object with HTTP information:
def handle(event, context):return {"body": {"message": "hello world"},"statusCode": 200,"headers": {"Content-Type": ["application/json"],"your-header": "your-value"}}
Straight response without body:
def handle(event, context):return {"message": "hello world"}# orreturn "my Message"
Stringified response body (AWS Lambda):
import jsondef handle(event, context):return {"body": json.dumps({"message": "hello world"}),"headers": {"Content-Type": ["application/json"],},"statusCode": 200,}
Getting data in Python
Using environment variables
Python runtime includes the os
, which enables you to access the environment variables you define in your namespaces or functions.
The following snippet returns the environment variable ENV
you specified in the function or namespace configuration:
import osdef handle(event, context):env_variable = os.getenv('ENV')return env_variable
Using event objects in Python
You can pass information through your HTTP request with event objects. They are composed of the following objects:
path
: str - Parameters defined in the path of the HTTP requestqueryStringParameters
: dict[str, str] - Query Strings parameters of the HTTP requestbody
: str - Body of the HTTP request, you will have to parse it in your handler to use it properly.headers
: dict[str, str] - HTTP request headersmethod
: string - HTTP method usedisBase64Encoded
: boolean - Whether the request body is base64 encoded.
def handle(event, context):# the event object is a Python dictquery_param = event['queryStringParameters']['parameter']query_body = event['body']# ...
Example of reading URL parameters:
curl https://myfunc/user/?id=1
Will fill the event with the following parameters:
event['path'] = "/user/"event['queryStringParameters'] = {"id": "1"}
Using data from CRON jobs in Python
CRON jobs share the same pattern as HTTP calls. You can find the information passed into the CRON body in the event object:
def handle(event, context):cron_body = event['body']# ...
Connecting to HTTP services in Python
You might need to get information or transmit data to an external service. The Scaleway Python runtime includes the urllib
library which enables you to connect to HTTP services without adding external libraries.
Refer to our guide on code packaging if you want to use requests.
GET
request example
from urllib import request, parse, errorimport osauth_token=os.getenv('X-AUTH-TOKEN') # You can pass tokens through os environment variable or secret environment variableurl={YOUR URL} # If you want a dynamic URL based on information sent to handle(), define the URL inside the functiondef handle(event, context):req = request.Request(url, method='GET')req.add_header('X-Auth-Token',auth_token)try:res = request.urlopen(req).read().decode()except error.HTTPError as e:res = e.read().decode()return {"body": json.loads(res),"headers": {"Content-Type": ["application/json"],},"statusCode": 200,}
POST
request example
from urllib import request, parse, errorimport osauth_token=os.getenv('X-AUTH-TOKEN') # You can pass tokens through os environment variable or secret environment variableurl={YOUR URL} # If you want a dynamic URL based on information sent to handle(), please define the URL inside the functiondef handle(event, context):data=json.dumps({"sample_key": "sample_value"}).encode('ascii')req = request.Request(url, data=data, method="POST")req.add_header('Content-Type', 'application/json')req.add_header('X-Auth-Token', auth_token)# Sending request to Instance APItry:res=request.urlopen(req).read().decode()except error.HTTPError as e:res=e.read().decode()return {"body": json.loads(res),"headers": {"Content-Type": ["application/json"],},"statusCode": 200,}try:res = request.urlopen(req).read().decode()except error.HTTPError as e:res = e.read().decode()return {"body": json.loads(res),"headers": {"Content-Type": ["application/json"],},"statusCode": 200,}
To use other libraries like request
, you need to upload your project with advanced methods (recommended)
or use a ZIP file.
Advanced Python examples
To find advanced and real-world examples for Serverless Functions, take a look at our dedicated repository.
Node
Returning a function result in Node
The following examples use CommonJS modules. If you use ES modules, refer to the dedicated section of this documentation.
There are multiple ways a response can return from a handler function:
- With body and statusCode. This response type sets the status code as
HTTP Response Code
, and body as the response’s body, headers asHeaders
.
Stringified body (like AWS Lambda
):
module.exports.myHandler = (event, context, callback) => {return {statusCode: 201,body: JSON.stringify({message: "async function",}),headers: {"Content-Type": "application/json",},}}
Not Stringified body (like AWS Lambda
):
module.exports.myHandler = (event, context, callback) => {return {statusCode: 201,body: {message: "async function",},headers: {"Content-Type": "application/json",},}}
- With object/entity (number, boolean, string…) without properties body and statusCode
module.exports.myHandler = (event, context, callback) => {return {body: "message",headers: {"Content-Type": ["text/plain"],},};// Orreturn JSON.stringify({ message: "message" });// ORreturn "Hello, world";// ORreturn 1; // true, false, undefined, null...};
Using the callback parameter:
module.exports.myHandler = (event, context, callback) => {const response = {statusCode: 201,body: {message: "async function",},headers: {"Content-Type": "application/json",},};// Successful responsecallback(undefined, response);// Error responsecallback(new Error("something bad happened..."));};
- With a
Promise
:
module.exports.myHandler = async (event, context, callback) => {return {statusCode: 201,body: {message: "async function",},headers: {"Content-Type": "application/json",},};}// ORmodule.exports.myHandler = (event, context, callback) => {const response = {statusCode: 201,body: {message: "async function",},headers: {"Content-Type": "application/json",},};return new Promise((resolve, reject) => {// do somethingif (err) return reject(err);return resolve(response);});};
Using environment variables in Node
If you need to pass information to your function you can use environment variables defined at the namespace or function level. In JavaScript, they are stored in the process.env
object:
module.exports.myHandler = (event, context, callback) => {const myParameter = process.env.MYPARAMETER;return {statusCode: 201,body: JSON.stringify({parameter: myParameter,}),headers: {"Content-Type": "application/json",},}}
Using event components
You can pass information through your HTTP request with the event object. It is composed of the following objects:
path
: string - Parameters defined in the path of the HTTP requestqueryStringParameters
: object - Query Strings parameters of the HTTP requestbody
: string - Body of the HTTP request, you will have to parse it in your handler to use it properlyheaders
: object - HTTP request headershttpMethod
: string - HTTP method usedisBase64Encoded
: boolean - Whether the request body is base64 encoded.
module.exports.myHandler = (event, context, callback) => {const queryStringParameters = event.queryStringParameters;const body = event.body;// ...};
Example of reading URL parameters:
curl https://myfunc/user/?id=1
Will fill the event with the following parameters:
event.path = "/user/"event.queryStringParameters = {"id": "1"}
Using data from CRON jobs in Node
CRON jobs share the same pattern as HTTP calls. You will find the information passed into the CRON body in the event object:
module.exports.myHandler = (event, context, callback) => {body = event.body;return {statusCode: 201,body: JSON.stringify({body: body,}),headers: {"Content-Type": "application/json",},};};
Connecting to HTTP services in Node
You might need to get information or transmit data to an external service. The following code snippets can be executed directly in Serverless Functions without adding external libraries.
Refer to our guide on code packaging, if you want to use fetch
, axios
, …
GET
request sample:
const https = require("https");exports.handle = async function (event, context) { let dataString = ""; const response = await new Promise((resolve, reject) => { const req = https.get( "https://pokeapi.co/api/v2/pokemon/ditto", function (res)<