NavigationContentFooter
Jump toSuggest an edit

Code examples for Serverless Functions

Reviewed on 22 July 2024Published on 18 October 2021

This page shows examples of functions in Python, Node, Golang, PHP, and Rust that can be used in your Serverless Functions projects.

Tip

You can find many more advanced examples and real-life use cases using Serverless products in our Serverless Examples repository.

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"}
# or
return "my Message"

Stringified response body (AWS Lambda):

import json
def 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 os
def 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 request
  • queryStringParameters: dict[str, str] - Query Strings parameters of the HTTP request
  • body: 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 headers
  • method: string - HTTP method used
  • isBase64Encoded: boolean - Whether the request body is base64 encoded.
def handle(event, context):
# the event object is a Python dict
query_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, error
import os
auth_token=os.getenv('X-AUTH-TOKEN') # You can pass tokens through os environment variable or secret environment variable
url={YOUR URL} # If you want a dynamic URL based on information sent to handle(), define the URL inside the function
def 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, error
import os
auth_token=os.getenv('X-AUTH-TOKEN') # You can pass tokens through os environment variable or secret environment variable
url={YOUR URL} # If you want a dynamic URL based on information sent to handle(), please define the URL inside the function
def 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 API
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,
}
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,
}
Note

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

Note

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 as Headers.

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"],
},
};
// Or
return JSON.stringify({ message: "message" });
// OR
return "Hello, world";
// OR
return 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 response
callback(undefined, response);
// Error response
callback(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",
},
};
}
// OR
module.exports.myHandler = (event, context, callback) => {
const response = {
statusCode: 201,
body: {
message: "async function",
},
headers: {
"Content-Type": "application/json",
},
};
return new Promise((resolve, reject) => {
// do something
if (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 request
  • queryStringParameters: object - Query Strings parameters of the HTTP request
  • body: string - Body of the HTTP request, you will have to parse it in your handler to use it properly
  • headers: object - HTTP request headers
  • httpMethod: string - HTTP method used
  • isBase64Encoded: 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)<