DEV Community

Cover image for Create a minimal API with json-server
Alonso Díaz
Alonso Díaz

Posted on

Create a minimal API with json-server

** It will take you longer to read this post than to create your api Seriously... **

In the great world of apis there are many ways to program your own api, express, laravel, etc, but...

How would you like to be able to create an api in less than a minute with all the http requests (post, put, delete, get) quickly and without so many code problems? (Yes, you could already have your api when you finish reading this post).

Well json-server is for you!

This can help us if we want to test a front-end in a simple way before connecting it completely with the back-end team or if you want to continue learning from the great and exciting path of the APIs (my case).

You only need a json file, a universal format that you've probably come across a lot of times up to this point :)

An example of a format could be with pizzas. Who in our area doesn't love them?

{"Pizza": [
     {
       "id": 1,
       "name": "Al Tono pizza",
       "description": "lots of tuna"
     },
     {
       "id": 2,
       "name": "italian",
       "description": "mama mia!",
     }
]}
Enter fullscreen mode Exit fullscreen mode

In the directory where you start working, (it doesn't matter if it's empty at this point), we execute the following command to install the package.

npm install json-server
Enter fullscreen mode Exit fullscreen mode

Now we create the json file (you can use the name of db.json to make it a bit more consistent with the example) and add our favorite products (I'll continue with the pizza)

The following is that through npx you must execute the following command

npx json-server --watch --port 5001 db.json
Enter fullscreen mode Exit fullscreen mode

(If you get an error, I suggest you run the following command)

npm install -g npx
Enter fullscreen mode Exit fullscreen mode

Where the port can be the one of your preference and db.json will vary by the name of your file.

Ready, you already have a functional api, and the best of all is that if you make post statements, it will remain saved in your file :)

Image description

If you want to have an example of how to create the requests, I leave you this documentation in postman!

Happy code!

Top comments (0)