Json server | blog eleven labs

Access from anywhere

You can access your fake API from anywhere using CORS and JSONP.

Add custom routes

Create a routes.json file. Pay attention to start every route with /.

Start JSON Server with –routes option.

json-server db.json --routes routes.json

Now you can access resources using additional routes.

Add middlewares

You can add your middlewares from the CLI using –middlewares option:

json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js

Alternative port

You can start JSON Server on other ports with the –port flag:

$ json-server --watch db.json --port 3004

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:

json-server uses 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:

Authentication flow 🔑

JSON Server Auth adds a simple JWT based authentication flow.

Authorization flow 🛡️

JSON Server Auth provides generic guards as route middlewares.

To handle common use cases, JSON Server Auth draws inspiration from Unix filesystem permissions, especialy the numeric notation.

  • We add 4 for read permission.
  • We add 2 for write permission.

Of course CRUD is not a filesystem, so we don’t add 1 for execute permission.

Banx. создание fake api с помощью json-server.

В данной статье поговорим про создание json сервера, который на основании JSON файла будет создавать соответствующие endpoint’ы. Также добавим модуль авторизации с помощью JWT.

Так как фронт всегда связан с каким-то API, любой фронтенд разработчик должен уметь создавать и поддерживать сервера. И владеть хотя бы пониманием, как устроен backend, и уметь создавать API с помощью NodeJS.

Bronze sponsors 🥉

Become a sponsor and have your company logo here

Cli usage

json-server [options] <source>

Options:
  --config, -c       Path to config file           [default: "json-server.json"]
  --port, -p         Set port                                    [default: 3000]
  --host, -H         Set host                             [default: "localhost"]
  --watch, -w        Watch file(s)                                     [boolean]
  --routes, -r       Path to routes file
  --middlewares, -m  Paths to middleware files                           [array]
  --static, -s       Set static files directory
  --read-only, --ro  Allow only GET requests                           [boolean]
  --no-cors, --nc    Disable Cross-Origin Resource Sharing             [boolean]
  --no-gzip, --ng    Disable GZIP Content-Encoding                     [boolean]
  --snapshots, -S    Set snapshots directory                      [default: "."]
  --delay, -d        Add delay to responses (ms)
  --id, -i           Set database id property (e.g. _id)         [default: "id"]
  --foreignKeySuffix, --fks  Set foreign key suffix, (e.g. _id as in post_id)
                                                                 [default: "Id"]
  --quiet, -q        Suppress log messages from output                 [boolean]
  --help, -h         Show help                                         [boolean]
  --version, -v      Show version number                               [boolean]

Examples:
  json-server db.json
  json-server file.js
  json-server http://example.com/db.json

https://github.com/typicode/json-server

You can also set options in a json-server.json configuration file.

Custom output example

To modify responses, overwrite router.render method:

You can set your own status code for the response:

Custom routes

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:

Database

GET /db

Deployment

You can deploy JSON Server. For example, JSONPlaceholder is an online fake API powered by JSON Server and running on Heroku.

Filter

Use . to access deep properties

Full text search

We can implement a search feature in our app using full-text search by simply adding a q query parameter.

Getting started

Install JSON Server

Create a db.json file with some data

Start JSON Server

json-server --watch db.json

Homepage

Returns default index file or serves ./public directory

GET /

How to use it?

This will take less than 5 minutes!

Installation

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){:rel=”nofollow noreferrer”}

{"articles":[{"id":1,"title":"Build an API using GO","authorId":2},{"id":2,"title":"Build an API using API Platform","authorId":1}],"comments":[{"id":1,"body":"Brilliant","articleId":1},{"id":2,"body":"Awesome","articleId":2}],"authors":[{"id":1,"username":"rpierlot","title":"Romain Pierlot"},{"id":2,"username":"qneyrat","title":"Quentin Neyrat"}]}

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:

Jwt payload 📇

The access token has the following claims :

Let’s get our hands dirty

server.js

varjsonServer=require('json-server')varserver=jsonServer.create()varrouter=jsonServer.router('db.json')varmiddlewares=jsonServer.defaults()functionsimpleAuth(req,res,next){if(req.headers.authorization){// user and password are stored in the authorization header// do whatever you want with themvaruser_and_password=newBuffer(req.headers.authorization.split(" ")[1],'base64').toString();// for example, get the usernamevaruser_only=user_and_password.split(':')[0];/*     *  I am not sure if you want to only send the user as a simple confirmation     *  or you want to apply your own logic, like, really authenticate/validate     *  the user against users database, static users .. etc     *     *  in production, it is recommended to validate the user by somehow.     */// and save it in the request for later use in the `router.render` methodreq.user=user_only;// continue doing json-server magicnext();}else{// it is not recommended in REST APIs to throw errors,// instead, we send 401 response with whatever erros// we want to expose to the clientres.status(401).send({error: 'unauthorized'})}}// this method overwrites the original json-server's way of response// with your custom logic, here we will add the user to the responserouter.render=function(req,res){// manually wrap any response send by json-server into an object// this is something like `res.send()`, but it is cleaner and meaningful// as we're sending json object not normal text/responseres.json({user: req.user,// the user we stored previously in `simpleAuth` functionbody: res.locals.data// the original server-json response is stored in `req.locals.data`})}// start setting up json-server middlewaresserver.use(middlewares)// before proceeding with any request, run `simpleAuth` function// which should check for basic authentication header .. etcserver.use(simpleAuth);// continue doing json-server magicserver.use(router);// start listening to port 3000server.listen(3000,function(){console.log('JSON Server is running on port 3000');})

db.json

License

MIT

Supporters

Module

If you need to add authentication, validation, or any behavior, you can use the project as a module in combination with other Express middlewares.

Module usage 🔩

If you go the programmatic way and use JSON Server as a module, there is an extra step to properly integrate JSON Server Auth :

⚠️ You must bind the router property db to the created app, like the JSON Server CLI does, and you must apply the middlewares in a specific order.

Operators

Add _gte or _lte for getting a range

Paginate

Use _page and optionally _limit to paginate returned data.

In the Link header you’ll get first, prev, next and last links.

Permisssions rewriter

The custom rewriter is accessible in json-server-auth/guards :

Relationships

We can see relationships using _embed & _expand parameters.

$ curl http://localhost:3000/articles?author=vincent&_embed=comments
[{"title": "GraphQL",
    "author": "vincent",
    "id": 3,
    "comments": [{"body": "nice",
        "articleId": 3,
        "id": 3
      },
      {"body": "great!",
        "articleId": 3,
        "id": 4
      }]}]$ curl http://localhost:3000/comments?_expand=article
[{"id": 1,
    "body": "Brilliant",
    "articleId": 1,
    "article": {"id": 1,
      "title": "Build an API using GO",
      "author": "qneyrat"}},
  {"id": 2,
    "body": "Awesome",
    "articleId": 2,
    "article": {"id": 2,
      "title": "Build an API using API Platform",
      "author": "rpierlot"}},
  ...
]

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.

Remote schema

You can load remote schemas.

Rewriter example

To add rewrite rules, use jsonServer.rewriter():

Singular routes

GET    /profile
POST   /profile
PUT    /profile
PATCH  /profile

Slice

Add _start and _end or _limit (an X-Total-Count header is included in the response)

Sponsor

Please help me build OSS👉GitHub Sponsors❤️

Исходники

Все исходники находятся на github, в репозитории:

Для того, чтобы посмотреть состояние проекта на момент написания статьи, нужно выбрать соответствующий тег — fake-api.

git checkout fake-api

Резюме

В данной статье рассмотрели создание фейкового сервера. Создали файл сервера с рядом environment параметров. Реализовали логику созданием и проверкой JWT токена. В конце привели демонстрацию работы реализованного сервера.

Создание api сервера

В качестве бэкенд сервера будем использовать json-server, который на основе json файла может выдать полноценный REST API.

В данном цикле статей, не будет реализовываться реальный сервер, например, NestJS, который уже есть в коробке Nx. Это связано с тем, что стоимость затрат на его разработку и поддержку слишком высока, и не дает каких-то видимых плюсов, для демонстрации тех аспектов, на которые направлены статьи.

Создание rest api на стороне сервера

Создадим файл сервера apps/russian/cabinet/api.server.ts:

В начале определяются enviroment переменные:

const PORT = process.env.PORT ?? 3000;
const DATA_PATH = process.env.DATA_PATH ?? __dirname.slice(process.cwd().length 1);
const DATA_NAME = process.env.DATA_NAME ?? 'api.db.json';
const JWT_SECRET_KEY = process.env.JWT_SECRET_KEY ?? 'MySecretKey';
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN ?? '1h';

Далее создаем server и подключаем все middleware’s:

const server = create();

const router = jsonRouter(join(DATA_PATH, DATA_NAME));
const middlewares = defaults();

server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
server.use(middlewares);

Потом определяем две точки. Первая, позволяет авторизоваться и получить JWT токен.

Вторая, смотрит, является ли endpoint методом авторизации, и если это не метод авторизации, проверяет наличие заголовка авторизации.

Тестирование

Для запуска сервера, будем использовать npm скрипт:

"start:api": "ts-node apps/russian/cabinet/api.server.ts"

Запустим сервер:

yarn start:api

Установка зависимостей

Уставном json-server:

yarn add -D json-server @types/json-server

Одним из основных вопросов при реализации сервера — какой будет авторизация. Пойдем по молодежному и добавим JWT.

yarn add -D jsonwebtoken @types/jsonwebtoken

Также добавим body-parser. Хоть он и есть в jsonwebtoken, для корректной поддержки типов, будем явно использовать пакет:

yarn add -D body-parser @types/body-parser

Mounting json server on another endpoint example

Alternatively, you can also mount the router on /api.

Conclusion

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!

Похожее:  Spring REST API -Part 3: Spring Security (Basic Authentication) | by Zia khalid | Medium

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *