How to create a REST API with serverless
In this example we will look at how to create a serverless REST API on AWS using SST.
Requirements
- Node.js 16 or later
- We’ll be using TypeScript
- An AWS account with the AWS CLI configured locally
Create an SST app
Let’s start by creating an SST app.
$ npx create-sst@latest --template=base/example rest-api
$ cd rest-api
$ npm install
By default, our app will be deployed to the us-east-1
AWS region. This can be changed in the sst.config.ts
in your project root.
import { SSTConfig } from "sst";
export default {
config(_input) {
return {
name: "rest-api",
region: "us-east-1",
};
},
} satisfies SSTConfig;
Project layout
An SST app is made up of two parts.
-
stacks/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
stacks/
directory of your project. SST uses AWS CDK, to create the infrastructure. -
packages/functions/
— App CodeThe code that’s run when your API is invoked is placed in the
packages/functions/
directory of your project.
Setting up our routes
Let’s start by setting up the routes for our API.
Replace the stacks/ExampleStack.ts
with the following.
import { Api, StackContext } from "sst/constructs";
export function ExampleStack({ stack }: StackContext) {
// Create the HTTP API
const api = new Api(stack, "Api", {
routes: {
"GET /notes": "packages/functions/src/list.handler",
"GET /notes/{id}": "packages/functions/src/get.handler",
"PUT /notes/{id}": "packages/functions/src/update.handler",
},
});
// Show the API endpoint in the output
stack.addOutputs({
ApiEndpoint: api.url,
});
}
We are creating an API here using the Api
construct. And we are adding three routes to it.
GET /notes
GET /notes/{id}
PUT /notes/{id}
The first is getting a list of notes. The second is getting a specific note given an id. And the third is updating a note.
Adding function code
For this example, we are not using a database. We’ll look at that in detail in another example. So internally we are just going to get the list of notes from a file.
Let’s add a file that contains our notes in packages/core/src/notes.ts
.
export default {
id1: {
noteId: "id1",
userId: "user1",
createdAt: Date.now(),
content: "Hello World!",
},
id2: {
noteId: "id2",
userId: "user2",
createdAt: Date.now() - 10000,
content: "Hello Old World! Old note.",
},
};
Now add the code for our first endpoint.
Getting a list of notes
Add a packages/functions/src/list.ts
.
import notes from "@rest-api/core/notes";
export async function handler() {
return {
statusCode: 200,
body: JSON.stringify(notes),
};
}
Here we are simply converting a list of notes to string, and responding with that in the request body.
Note that this function need to be async
to be invoked by AWS Lambda. Even though, in this case we are doing everything synchronously.
Getting a specific note
Add the following to packages/functions/src/get.ts
.
import notes from "@rest-api/core/notes";
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
export const handler: APIGatewayProxyHandlerV2 = async (event) => {
const note = notes[event.pathParameters.id];
return note
? {
statusCode: 200,
body: JSON.stringify(note),
}
: {
statusCode: 404,
body: JSON.stringify({ error: true }),
};
};
Here we are checking if we have the requested note. If we do, we respond with it. If we don’t, then we respond with a 404 error.
Updating a note
Add the following to packages/functions/src/update.ts
.
import notes from "@rest-api/core/notes";
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
export const handler: APIGatewayProxyHandlerV2 = async (event) => {
const note = notes[event.pathParameters.id];
if (!note) {
return {
statusCode: 404,
body: JSON.stringify({ error: true }),
};
}
const data = JSON.parse(event.body);
note.content = data.content;
return {
statusCode: 200,
body: JSON.stringify(note),
};
};
We first check if the note with the requested id exists. And then we update the content of the note and return it. Of course, we aren’t really saving our changes because we don’t have a database!
Now let’s test our new API.
Starting your dev environment
SST features a Live Lambda Development environment that allows you to work on your serverless apps live.
$ npm run dev
The first time you run this command it’ll take a couple of minutes to do the following:
- It’ll bootstrap your AWS environment to use CDK.
- Deploy a debug stack to power the Live Lambda Development environment.
- Deploy your app, but replace the functions in the
packages/functions/
directory with ones that connect to your local client. - Start up a local client.
Once complete, you should see something like this.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-rest-api-ExampleStack: deploying...
✅ dev-rest-api-ExampleStack
Stack dev-rest-api-ExampleStack
Status: deployed
Outputs:
ApiEndpoint: https://2q0mwp6r8d.execute-api.us-east-1.amazonaws.com
The ApiEndpoint
is the API we just created.
Let’s test our endpoint using the integrated SST Console. The SST Console is a web based dashboard to manage your SST apps Learn more about it in our docs.
Go to the API explorer and click the Send button of the GET /notes
route to get a list of notes.
Note, The API explorer lets you make HTTP requests to any of the routes in your Api
construct. Set the headers, query params, request body, and view the function logs with the response.
You should see the list of notes as a JSON string.
To retrieve a specific note, Go to GET /notes/{id}
route and in the URL tab enter the id of the note you want to get in the id field and click the Send button to get that note.
Now to update our note, we need to make a PUT
request, go to PUT /notes/{id}
route.
In the URL tab, enter the id of the note you want to update and in the body tab and enter the below json value and hit Send.
{ "content": "Updating my note" }
This should respond with the updated note.
Making changes
Let’s make a quick change to our API. It would be good if the JSON strings are pretty printed to make them more readable.
Replace packages/functions/src/list.ts
with the following.
import notes from "@rest-api/core/notes";
export async function handler() {
return {
statusCode: 200,
body: JSON.stringify(notes, null, " "),
};
}
Here we are just adding some spaces to pretty print the JSON.
If you head back to the GET /notes
route and hit Send again.
You should see your list of notes in a more readable format.
Deploying your API
To wrap things up we’ll deploy our app to prod.
$ npx sst deploy --stage prod
This allows us to separate our environments, so when we are working in dev
, it doesn’t break the app for our users.
Once deployed, you should see something like this.
✅ prod-rest-api-ExampleStack
Stack prod-rest-api-ExampleStack
Status: deployed
Outputs:
ApiEndpoint: https://ck198mfop1.execute-api.us-east-1.amazonaws.com
Run the below command to open the SST Console in prod stage to test the production endpoint.
npx sst console --stage prod
Go to the API explorer and click Send button of the GET /notes
route, to send a GET
request.
Cleaning up
Finally, you can remove the resources created in this example using the following command.
$ npx sst remove
And to remove the prod environment.
$ npx sst remove --stage prod
Conclusion
And that’s it! You’ve got a brand new serverless API. A local development environment, to test and make changes. And it’s deployed to production as well, so you can share it with your users. Check out the repo below for the code we used in this example. And leave a comment if you have any questions!
For help and discussion
Comments on this example