ExpressJS — RESTful API simple and quick
Making an api is useful when we want our projects to be open. So people can use our code to make something of their own.
There are a lot of ways to make this happen, here we will be using expressjs and our data will be local, meaning no need for a database. Under normal circumstances it would be optimal to have an external database.
First we need to open a server which is simple. Theres only a few lines of code need for that.
With just that we get a server up and running, now we handle routes.
We will set up the api queries as routes, this way the api as more exposure, allowing it not only to be tested but used with any browser.
With that when a user calls for a page we will be able to serve it on the middleware of this functions.
To do this we will simple use a array of objects in the code. This is where we could connect to a database and request data from there.
We need to define how should the api be called and what are the available functions for public use.
Listing users:
localhost:5000/api/listusers
Add a user:
localhost:5000/api/adduser?username='username'&email='usersemail'
Delete a user:
localhost:5000/api/deleteuser?id=1
Inspect a user:
localhost:5000/api?id=1
Now that we know how the request will come we can make the code for the public functions.
To list users we just need to send the array. But to add them into the array we actualy need to do some code. We will be using the push() method and parse the data from the query to the new object.
To delete a user is a bit more tricky, first we need to get the id that’s to be deleted, then find such item in the array, and then actually delete it.
For that purpose we will use splice(), indexOf() and the find() method.
To inspect a specific user we will also need to use find().
In the end your code should look something like this.