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 startLink to this anchor
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
PythonLink to this anchor
Returning a function result in PythonLink to this anchor
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 PythonLink to this anchor
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 PythonLink to this anchor
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 PythonLink to this anchor
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 PythonLink to this anchor
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 examplesLink to this anchor
To find advanced and real-world examples for Serverless Functions, take a look at our dedicated repository.
NodeLink to this anchor
Returning a function result in NodeLink to this anchor
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..."));};