Accepting arguments
You can do lots with the hello world functions you built in the last exercise. Accepting arguments and data will let you do even more.
That's when cloud functions become as powerful as your other JavaScript.
We'll explore 3 ways to accept parameters:
- As part of the URL path
- As a query string
- As a data payload
Vercel
Vercel's filename-based routing gives you the simplest approach to path params that I've ever seen đ name your file as /api/[param1]/[param2].js
and anything in square brackets becomes a named value.
You get URL queries and data payloads in the req
object.
Exercise
Create a new file in your hello world project, call it [name].js
or [name].ts
. Return a Hello <name>
string.
Make your function return Hello <name>, beautiful day today <emoji>
where the emoji comes from query or body params. Default to query, use body if emoji is undefined.
Use req.query
for path and query params. Use req.body
for body payload params.
Deploy with vercel
, use default answers to prompts.
Try your function
Leave payload empty for GET requests, valid JSON for POST.
Solution
Netlify
Best I can tell, Netlify doesn't support path params. âšī¸
Query and body params work though and they're all you need. The URLs aren't that pretty anyway.
Exercise
Add a happy-day.js
file to your hello world project.
Make your function return Hello <name>, beautiful day today <emoji>
where the emoji comes from query or body params. Default to query, use body if emoji is undefined.
Use event.queryStringParameters
for query params and event.body
for the body payload. You'll need to JSON.parse
that one.
Deploy with netlify deploy
, use defaults to answer any prompts.
Your function is live at <domain>/.netlify/functions/<filename>
Try your function with these terminal commands:
Try your function
Leave payload empty for GET requests, valid JSON for POST.
Solution
AWS Lambda
AWS Lambda lets you accept all 3 types of params.
Exercise
Move into exercise-2
from the serverless-workshop-exercises GitHub repository.
Create a src/happy-day.ts
file. Use the same code as your Netlify solution from the previous exercise. Declare the event arg as APIGatewayEvent
and change to a TypeScript export
exports.handler = async (event) => {// becomesexport const handler = async (event: APIGatewayEvent) => {
TypeScript will force you to think about undefined params as well. We ignored that with Netlify.
Add your new method to serverless.yml
and configure:
- the handler path
- a GET event
- a POST event
- a parametrized path with
{name}
Try reading the name path param from event.pathParameters
Deploy with yarn deploy
or npm run deploy
Try your function
Leave payload empty for GET requests, valid JSON for POST.
Solution
https://github.com/Swizec/serverless-workshop-exercises/tree/exercise-2-solution