How to create a REST API in TypeScript with serverless
In this example we’ll look at how to create a serverless REST API with TypeScript on AWS using Serverless Stack (SST). We also have a a JavaScript version of this example as well.
Requirements
- Node.js >= 10.15.1
- 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-serverless-stack@latest --language typescript rest-api-ts
$ cd rest-api-ts
By default our app will be deployed to an environment (or stage) called dev
and the us-east-1
AWS region. This can be changed in the sst.json
in your project root.
{
"name": "rest-api-ts",
"stage": "dev",
"region": "us-east-1"
}
Project layout
An SST app is made up of two parts.
-
lib/
— App InfrastructureThe code that describes the infrastructure of your serverless app is placed in the
lib/
directory of your project. SST uses AWS CDK, to create the infrastructure. -
src/
— App CodeThe code that’s run when your API is invoked is placed in the
src/
directory of your project.
Setting up our routes
Let’s start by setting up the routes for our API.
Replace the lib/MyStack.ts
with the following.
import * as sst from "@serverless-stack/resources";
export default class MyStack extends sst.Stack {
constructor(scope: sst.App, id: string, props?: sst.StackProps) {
super(scope, id, props);
// Create the HTTP API
const api = new sst.Api(this, "Api", {
routes: {
"GET /notes": "src/list.main",
"GET /notes/{id}": "src/get.main",
"PUT /notes/{id}": "src/update.main",
},
});
// Show the API endpoint in the output
this.addOutputs({
ApiEndpoint: api.url,
});
}
}
We are creating an API here using the sst.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 src/notes.ts
.
interface Note {
noteId: string;
userId: string;
createdAt: number;
content: string;
}
const notes: { [key: string]: Note } = {
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.",
},
};
export default notes;
Now add the code for our first endpoint.
Getting a list of notes
Add a src/list.ts
.
import { APIGatewayProxyResult } from "aws-lambda";
import notes from "./notes";
export async function main(): Promise<APIGatewayProxyResult> {
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 src/get.ts
.
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
import notes from "./notes";
export async function main(
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> {
const note =
event.pathParameters && event.pathParameters.id
? notes[event.pathParameters.id]
: null;
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 src/update.ts
.
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
import notes from "./notes";
export async function main(
event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> {
const note =
event.pathParameters && event.pathParameters.id
? notes[event.pathParameters.id]
: null;
if (!note) {
return {
statusCode: 404,
body: JSON.stringify({ error: true }),
};
}
if (event.body) {
const data = JSON.parse(event.body);
note.content = data.content || note.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.
$ npx sst start
The first time you run this command it’ll take a couple of minutes to deploy your app and a debug stack to power the Live Lambda Development environment.
===============
Deploying app
===============
Preparing your SST app
Transpiling source
Linting source
Deploying stacks
dev-rest-api-ts-my-stack: deploying...
✅ dev-rest-api-ts-my-stack
Stack dev-rest-api-ts-my-stack
Status: deployed
Outputs:
ApiEndpoint: https://rxk5buowgi.execute-api.us-east-1.amazonaws.com
The ApiEndpoint
is the API we just created. Now let’s get our list of notes. Head over to the following in your browser. Make sure to replace the URL with your API.
https://rxk5buowgi.execute-api.us-east-1.amazonaws.com/notes
You should see the list of notes as a JSON string.
And use the following endpoint to to retrieve a specific note.
https://rxk5buowgi.execute-api.us-east-1.amazonaws.com/notes/id1
Now to update our note, we need to make a PUT
request. Our browser cannot make this type of request. So use the following command in your terminal.
curl -X PUT \
-H 'Content-Type: application/json' \
-d '{"content":"Updating my note"}' \
https://rxk5buowgi.execute-api.us-east-1.amazonaws.com/notes/id1
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 src/list.ts
with the following.
import { APIGatewayProxyResult } from "aws-lambda";
import notes from "./notes";
export async function main(): Promise<APIGatewayProxyResult> {
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 /notes
endpoint.
https://rxk5buowgi.execute-api.us-east-1.amazonaws.com/notes
You should see your list of notes in a more readable format.
Deploying your API
Now that our API is tested, let’s deploy it to production. You’ll recall that we were using a dev
environment, the one specified in our sst.json
. However, we are going to deploy it to a different environment. This ensures that the next time we are developing locally, it doesn’t break the API for our users.
Run the following in your terminal.
$ npx sst deploy --stage prod
Cleaning up
Finally, you can remove the resources created in this example using the following commands.
$ npx sst remove
$ 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!
Example repo for reference
github.com/serverless-stack/serverless-stack/tree/master/examples/rest-api-tsFor help and discussion
Comments on this exampleMore Examples
APIs
- How to create a REST API with serverless
- How to create a WebSocket API with serverless
- How to create a REST API in TypeScript with serverless
- How to create a REST API in Golang with serverless
- How to add a custom domain to a serverless API