Tutorial on the basics of NextJS for building a website.
Hello, Today I’m going to talk about json-server, what is it? why use it? and especially how to use it?
json-server is a cool
npm module, that provides an Express server that serves a JSON API.
Why use it?
POST …etc.), and you want to persist your updates. Unfortunately, you can't do all of this using a static file, you need to look for a way to make it dynamic. So, unless your pal who's developing the API has finished their work, you're gonna need some serious help.
json-server, it allows you to mock the API, and provide dynamic access to data. By dynamic, I mean that we can read, add, update, and delete data (
It provides common URL use cases like:
- Routes (
- Filters (
- Pagination (
- Full text search (
- Relationships (
and other miscellaneous stuff like:
- Ability to access remote schemas
- Randomly generated data
- Custom routes
- Ability to use
json-serveras a module in your NodeJS server
Okay, let's get to it.
How to use it?
This will take less than 5 minutes!
- NodeJS &
- An API consumer (Your code,
curl, postman, or simply your browser)
It's pretty straightforward to set up:
To fill it in, we can either do it by hand or use a random json generator (my favorite is json-generator)
Now we can run
json-server so that we can access the endpoints that
json-server created for us
Great, we've set up our API mock. Now we can test our endpoints:
We can use almost all kinds of URIs to perform requests:
For example, to insert (create) a new author, we might use:
To read an article with article id 2:
GET http://localhost:3000/articles/2. The same URI would be used for
DELETE, to update and delete, respectively.
Now, when it comes to creating a new comment in an article, one option might be:
POST http://localhost:3000/comments And that could work to create a comment, but it's arguably outside the context of an article.
As a matter of fact, this URI is not as intuitive as it could be. It could be argued that the following URI would offer better clarity:
POST http://localhost:3000/articles/1/comments. Now we know we're creating a comment in article id 1.
Same with creating an article by author id 3:
Filters, sort & operators
Filtering is done using query parameters:
Sort is as easy as adding
desc) query parameters:
(Assuming we have added the
likes field to each article). The order is ascending by default.
In case we want to sort by multiple properties, we can write our properties separated by a comma:
Operators are suffixes used to augment our query parameters:
_gte(greater than or equal) and
_lte(less than or equal):
GET http://localhost:3000/comments?score_gte=5(assuming we have a
scorefield in the comments)
_ne(not equal) negation of an expression
_likeis an operator that can be applied to string properties, it gives the same result as an
We can use the built-in query parameters
_limit to paginate our results.
X-Total-Count and the
Link header that contain links to the first, next and last pages.
Full text search
We can implement a search feature in our app using full-text search by simply adding a
q query parameter.
We can see relationships using
_embedallows us to see the children resources like
_expandallows us to see the parent resources like
Until now, we've seen only the routes part of
json-server, there are a lot more things we can do, let's see what's next.
Randomly generated data
The basic example in Typicode's docs presents a simple script that generates the
users endpoint. Here we are going to write endpoints that serve randomly generated data using a data faker module. Personally, I use faker.js, but there are others that you can explore like Chance and Casual.
The random aspect of the generation occurs only once, and that's when we run the script. This means that
json-server won't give us a different response for each request. Eventually, we have to install our fake data tool, then write the generation script:
Keep in mind that the script must export a function that exclusively returns an object with keys (endpoints) inside.
Then run json-server by giving it the generation script:
And the results would be something like:
And we can still perform requests on it as we've seen in the routes section.
Let's imagine we are supposed to perform requests on several different endpoints on our future API, and these endpoints don't have the same URIs:
json-server allows us to specify route rewrites. We can address this problem by using a map that resolves the actual routes in our json schema:
So, when we start
json-server it shows us the route rewrites we are using :
Now we can perform our custom requests to see the results:
In case we want to augment our
json-server instance with a specific behavior, we have the possibility to do so using custom middlewares, these middlewares are passed to the express server the same way we would do it when developing a classic express app. In this section, we're going to explore a useful example of a feature that is usually necessary.
Imagine we want to access a resource on the API, but it turns out that this resource is secured. We can say that it's just about data and assume that we'll be satisfied by just returning it, then we use
json-server to provide the data without worrying about security. But, we know that something's odd, we want our app to be ready when our future API is ready, in order to test the whole thing together. So, instead of bypassing it, let's use middlewares to set up an authentication layer.
Now run the
json-server command with the
--middlewares option accepts a list of files.
--middlewares file1.js file2.js file3.js.
Now let's test our authentication layer:
And we can see
json-server's log with the
401 HTTP status:
When we display the headers of this response, we recognize this header
WWW-Authenticate: Basic realm="Access to the API":
Here is what Mozilla Developer Network tells about it:
Proxy-Authenticateresponse headers define the authentication method that should be used to gain access to a resource. They need to specify which authentication scheme is used so that the client that wishes to authorize knows how to provide the credentials.
Then we test again, and this time we add credentials to our request (Notice:
--user option is not restricted to basic authentication, we can do other types of authentication, see here):
Great! Obviously, it's a
200 HTTP status :-D
As a NodeJS module
json-server is an
express application, which means that we can use it in an existing node/express app to achieve special behaviors. Here is a simple example that shows how to customize the logger:
morgan for logs, and the default format that it uses is the
dev log format, which doesn't expose all the info that we want, we need to use the standard Apache combined log outpout format instead:
Then we run our server:
Here we can see our custom logs in the console:
json-server has drastically decreased the time of scaffolding an API. Amongst the possibilities that we've seen, there are lots of use cases you can explore in order to use json-server, like logging customization, testing, reconciliation between micro-services, serverless applications ...etc.
I hope this post did shed some light on how we can use json-server. I tried to bring some useful use cases we encounter every day. If you still want to learn more about using it or even its inner working, I recommend exploring its github project.
Thanks for reading!