How to Build an Express API with GET and POST Routes
In this lesson, we'll use the routing capabilities Express gives us to create GET and POST routes that interact with the mock data listings array we've established.
Get the project source code below, and follow along with the lesson material.
Download Project Source CodeTo set up the project on your local machine, please follow the directions provided in the README.md
file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.
Creating GET and POST Express routes
📝 This lesson's quiz can be found - here.
🗒️ Solutions for This lesson's quiz can be found - here.
📃 Grab a cheatsheet that summarizes creating a simple GET and POST route with Express - here.
With our mock listings
array defined, we'll attempt to have our Express server give us the capability to GET and POST changes to this mock data array.
Like we've seen for the index route (/
) in the src/index.ts
file, Express gives us the capability to creates routes which refer to how different endpoints respond to client requests. We're going to create two new separate routes:
- A
/listings
route with which we can retrieve the listings collection. - A
/delete-listing
route with which we can delete a specified listing.
Get listings
To GET the listings information in an Express route, we can do just like what we've done when we sent the 'hello world'
message for the index route. We'll first import the listings
array in our src/index.ts
file.
import { listings } from "./listings";
Then use the app.get()
method to create a new /listings
route that is to simply return the listings
array.
app.get("/listings", (_req, res) => {
res.send(listings);
});
With the server being run, if we head to the browser and navigate to the /listings
route, we'll be presented with our mock listings data array.

We're using the JSON Viewer Chrome Extension to humanize this data and make it more readable.
Delete a listing
We'll now create functionality to help delete a listing from our mock data.
In a standard REST API, the GET method is often used to request data. Though many other methods exist, we'll use the POST method to specify a route that can have data be sent to the server to conduct an action. In this case, we'll look to have the id
of a listing be passed in which will be used to delete that particular listing. For our server to access the data in our POST request, we'll install a middleware to help parse the request body. We'll use the popular bodyParser
library which can be installed alongside its type declaration file.
This lesson preview is part of the The newline Guide to Building Your First GraphQL Server with Node and TypeScript course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to The newline Guide to Building Your First GraphQL Server with Node and TypeScript, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

[00:00 - 00:16] With our Listening's array now defined, we're going to attempt to have our express server give us the capability to get and post changes to this mock data array. So let's head back to the index.ts file in our source folder.
[00:17 - 00:48] Like we've seen for the index routes, express gives us the capability to create routes which refer to how different endpoints respond to client requests. We're going to create two new separate routes, a listings route, which allows us to retrieve the entire listings collection and a delete listing routes, with which we can delete a specified listing.
[00:49 - 01:11] To get the listings information in express routes, we can do just like we've done when we sent the hello world message for the index route, or in this case, how you sent just a message that says 1 plus 2 equals 3. But first, what we're going to do is we're actually going to import the listings array to actually make the data available in our index.ts file.
[01:12 - 01:30] Now, we'll use the get function in our app server instance to denote that we're creating a get request for a search and routes. This routes would be slash listings.
[01:31 - 01:45] In our callback function, we'll declare the request parameter and the response parameter. And like we've done before, we'll specify the underscore symbol in our request parameter since we won't be using it.
[01:46 - 01:59] In our callback function, we'll be simple, and we'll simply return the response.send function and just pass in the listings array as is. We won't be making any changes to the array.
[02:00 - 02:15] In our terminal, we'll now run our server. With our server successfully running and we see the console log message, we'll head to the browser and now navigate to the slash listings routes.
[02:16 - 02:28] We're now presented with our mock listings data array. Now, we are using the JSON viewer Chrome extension that humanizes this data, makes it more readable, and adds a little bit of styling.
[02:29 - 02:42] But regardless, you should now be able to see the listings data array on the client. Let's now create some functionality that allows us to delete a listing from our mock data array.
[02:43 - 03:01] In a standard REST API, the get method is often used to request data. Though many other methods exist, we'll use the post method to specify a route that can have data be sent to the server to conduct an action.
[03:02 - 03:21] In this case, we'll look to have the idea of a listing be passed in our post request, which will be used to delete that particular listing. In order for our server to access the data in our post request, we'll look to install a middleware to help parse the request body.
[03:22 - 03:35] We're going to use the popular body parser utility library. So we'll exit the server in our terminal, and first install the body parser package as a dependency.
[03:36 - 03:56] We'll then install its type declaration file as a dev dependency. In our index.ts file, we'll now import body parser from the body parser package.
[03:57 - 04:14] To use middleware in our express server, we'll use the app.use function that express provides. This use function can be used in the app server instance.
[04:15 - 04:31] In our middleware function, we'll pass in body parser dot JSON. This body parser dot JSON function will help parse incoming requests as JSON and expose the resulting objects on request dot body.
[04:32 - 04:53] We'll now set up the post request for the new delete listing routes. We'll specify the callback function like we've done before, and attempt to access both the request parameter and the response parameter.
[04:54 - 05:03] Now we expect the ID of the item or listing to be deleted is to be sent as part of the request body. So we'll attempt to access that ID.
[05:04 - 05:17] Now request is actually inferred to be of the interface type request from our express package. But body doesn't have an explicit type.
[05:18 - 05:23] It's inferred to be of type any. As a result, the ID doesn't have a particular type here as well.
[05:24 - 05:37] So what we'll do is we'll simply try to define or explicitly define the ID variable we're creating as a string type. When it comes to actually finding the listing we want to delete, there's a few ways of doing this.
[05:38 - 05:52] But we keep a simple and we'll use a very simple for loop. Here we're saying iterate through the listings array.
[05:53 - 06:05] And at any moment in time, if that iterated listing item ID is equal to the ID from our request body, we can actually do something here. And what we intend to do is we intend to do two things.
[06:06 - 06:12] We want to actually delete that listing. But we also want to send the deleted listing.
[06:13 - 06:24] So we'll use the response.send function. But in this function, we'll pass in listings.splice, the index of the listing we want to delete.
[06:25 - 06:32] And since we want to delete a single listing, we'll just specify one as the second argument. The array splice function deletes an item.
[06:33 - 06:47] But it also returns the deleted item, which is exactly what we want here. Now, if we actually manage to go through the entire listings array and we don't actually find the ID we want to delete, we'll get to the bottom of our function here.
[06:48 - 07:08] And we'll send a simple response that says failed to delete listing. There's a few ways we can try and make this post command happen from building a UI to interact with a server to using tools like Postman.
[07:09 - 07:26] For now, however, we'll simply use Curl in our command line to simply test this post request. Curl is installed by default on many systems and is an easy way for us to interact with APIs.
[07:27 - 07:43] OS X users should already have Curl installed, but will also provide a link in our lesson documentation with where Windows users can download and install Curl. The simplest way to use Curl is to run Curl followed by the URL we want to interact with.
[07:44 - 07:58] Now, since we actually have to pass data with our request, we're going to introduce some arguments into our Curl request. The first one being the dash X flag, which allows us to specify which HTTP method to use.
[07:59 - 08:06] We'll say post since we intend to make a post request. We'll declare the URL of our endpoint right after.
[08:07 - 08:28] This URL is HTTP localhost 9000/delete listing. Now, the next flag we're going to add, the dash H flag, allows us to set a header for our HTTP request.
[08:29 - 08:52] We'll specify content type, application JSON, to inform the server that the body of the request is JSON. And then finally, we're going to add the dash D flag to pass the body of our request.
[08:53 - 09:06] Here, we'll specify the data we want to pass within quotes. We'll pass in an ID of the particular listing that we actually want to delete.
[09:07 - 09:23] For this example, we'll just say 001, which is a reference to the first listing object in our mock listings data array. Now, to be able to run this Curl command, we actually need to have our server running.
[09:24 - 09:37] So we're going to open a new tab in our terminal and then navigate down to the server directory within our tiny house project. And then we'll actually run the project with npm run start.
[09:38 - 09:55] With our server running in the tab below and the tab above, we can now actually press enter to run our Curl command. We can probably see just from the results here that our Curl command was successful, because we actually have the returned deleted listing be sent back to us.
[09:56 - 10:07] The ID saying 001 and all the other fields about that particular listing. Now, when we head to the browser, refresh the slash listings route in our local 9000 URL.
[10:08 - 10:17] We can actually see that the first object in our listings array has now actually been deleted. We've just successfully created a get request to retrieve all the listings.
[10:18 - 10:34] And now we've completed to create this post request, which allows us to delete a listing from our mock data array. Now, before we close this lesson, the only thing left for us to do is we'll remove the initial get request we set up for our index route.
[10:35 - 10:50] And we'll also remove the variables we declared needed in that route, 1 and 2. [ Silence ]