10 Tweets Jan 31, 2023
How to create the simple REST API in Express
Thread🧵👇
In one of the previous tutorials, we explained how to create a simple Express server.
Now I'll show you how to create a simple REST API in Express.
It's a follow-up to the simple Express server tutorial.
Below is the code of the simple Express server we created in our previous tutorial.
It runs on port 3000 and has one GET endpoint defined that returns "hello world".
Let's add more functionality.
Let's install two packages.
1. body-parser - It's a request body parsing middleware for NodeJs.
2. Cors - middleware that can be used to enable CORS with various options.
You can see the modified code below.
We're requiring both packages and use "app.use" methods to use them as middleware.
Middleware runs before other handlers are executed on the request.
We also defined a "users" array. We're going to use it to hold our data.
In real world scenario, you'll use a database for this purpose to make changes persistent.
The following code will return the specific user by its Id.
We're using for of loop there to get the user information from the array.
The code below shows the POST example.
We're using the req.body method to read user data from the request and then push data to the array.
Now let's delete the user from the array.
Again we're getting the user id from the request and using the array filter method to delete the specified users from the array.
Hope you enjoyed this thread.
If you found this thread useful, follow @Rapid_API 🐙💙

Loading suggestions...