iTranslated by AI
Dec 6th: Getting Started with Netlify Functions
This article is for Day 6 of the Serverless Hello World Advent Calendar 2020.
In this post, I will implement an HTTP API using Netlify Functions.
Creating a Function
Netlify Functions doesn't seem to provide a specific code generator, so I will write the code manually.
$ mkdir helloworld
$ cd helloworld
$ git init
$ mkdir functions
First, specify the directory where Netlify should load functions from.
[build]
functions = "functions"
Next, place the function's main body in the functions directory created earlier.
'use strict';
exports.handler = async function (event, context) {
const body = event.body ? JSON.parse(event.body) : {};
const name = event.queryStringParameters.name || body.name || '';
return {
statusCode: 200,
body: JSON.stringify({message: `Hello ${name}!`}),
};
};
$ git add .
$ git commit
Push to GitHub and register with Netlify. No special configuration specific to Netlify Functions is required.
After waiting a moment for the deployment to complete, let's test it using cURL.
The URL format will be {Site URL}/.netlify/functions/{Function name}.
curl -v 'https://friendly-pike-1b50fb.netlify.app/.netlify/functions/hello?name=world'
* Trying 18.136.21.181:443...
* TCP_NODELAY set
* Connected to friendly-pike-1b50fb.netlify.app (18.136.21.181) port 443 (#0)
...(omitted)...
> GET /.netlify/functions/hello?name=world HTTP/2
> Host: friendly-pike-1b50fb.netlify.app
> user-agent: curl/7.68.0
> accept: */*
>
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
* old SSL session ID is stale, removing
* Connection state changed (MAX_CONCURRENT_STREAMS == 150)!
< HTTP/2 200
< cache-control: no-cache
< date: Tue, 15 Dec 2020 20:12:46 GMT
< content-length: 26
< content-type: text/plain; charset=utf-8
< age: 0
< server: Netlify
< x-nf-request-id: 738de0d0-bc2d-42da-b98b-17be5b7e48cc-38804153
<
* Connection #0 to host friendly-pike-1b50fb.netlify.app left intact
{"message":"Hello world!"}%
I was able to deploy the hello function on Netlify.
The ability to run AWS Lambda-based functions on the same domain without worrying about CORS or other issues makes it very convenient.
Discussion