Build a REST API(s) from a JSON file with Authentication
Creating an API(s) can be time-consuming. But there are packages such as json-server, hai-server, etc. which helps us to build a full fake REST API with zero coding in less than 30 seconds.
These tools are really helpful for front-end developers who need a quick back-end for prototyping and mocking. Here we are going to talk about hai-server.
Install hai-server on your local machine. For further info read here.
npm install -g hai-server
Create a db.json
file with some data
Start hai-server
by running the following command in the terminal.
hai-server --watch db.json
Now if you go to http://localhost:3000/posts/1, you’ll get
{ "id": 1, "title": "hai-server", "author": "sumn2u" }
How to restrict access to an API?
Create a file name auth.json
similar to the one shown below. Provide your own secretKey
, expiresIn
, and collection of authenticated users. Here the authenticatedURL
indicates the collection of URLs that needs authorization and authenticationURL
is the URL to get access_token
. Thus obtained access_token
can be used for accessing the authorized API(s).
Note: We are restricting the
/comments
api over here.
Run the hai-server
in your terminal.
hai-server --watch db.json --auth auth.json --port 3000
How to login?
You can log in by sending a POST request to
POST http://localhost:3000/auth/login
with the following data.
Note: We can pick any user data from the list of users of the
auth.json
file.
{
"email": "nilson@email.com",
"password":"nilson"
}
You should receive an access token with the following format
{
"access_token": "<ACCESS_TOKEN>"
}
You should send this authorization with any request to the protected endpoints
Authorization: Bearer <ACCESS_TOKEN>
You can call a restricted API from the access_token
.
Conclusion
In this way, we can create a full fake API(s) with zero configuration and can also implement authorization to restrict access.