JSON Server

repository·main·Indexed 13 days ago

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

A tool for creating a full fake REST API with zero coding using a JSON or JSON5 file as a database. Version 1.0.0-beta.15 provides built-in support for advanced querying, pagination, relationships, and static file serving. It includes a programmatic API via `createApp()` and a `Service` class for managing CRUD operations, resource embedding, and complex filtering using operators like `lt`, `lte`, `gt`, `gte`, `ne`, `in`, `contains`, `startsWith`, and `endsWith`.

Tokens
4.6K
Snippets
21
Records
23
Agent score
100%

What's inside JSON Server

  1. Quickstart: Create and run a mock REST API

    main

    To use JSON-Server, follow these steps:

    1. Create a db.json or db.json5 file containing your data. Each top-level key in the JSON object represents a resource.
    2. Start the server using npx json-server <filename>.

    By default, the server starts at http://localhost:3000.

    {
      "posts": [
        { "id": "1", "title": "a title", "views": 100 },
        { "id": "2", "title": "another title", "views": 200 }
      ],
      "comments": [
        { "id": "1", "text": "a comment about post 1", "postId": "1" }
      ],
      "profile": {
        "name": "typicode"
      }
    }
    npx json-server db.json
  2. Migrate from v0.x to v1.x

    main

    If you are upgrading from json-server v0.x, be aware of the following breaking changes:

    • ID handling: id is always a string and is auto-generated if not provided.
    • Pagination: Use _per_page with _page instead of the deprecated _limit parameter.
    • Relationships: Use _embed instead of _expand for including related resources.
    • Request delays: The --delay CLI option has been removed. Use browser DevTools (Network tab > throttling) to simulate latency.
  3. Understand resource embedding

    main

    Embedding allows you to include related data in your API responses. The Service class uses the embed option in find and findById to perform this.

    • One-to-One (Belongs To): If the related resource name is singular (e.g., author), the service looks for a foreign key like authorId on the current item and embeds the matching object from the authors collection.
    • One-to-Many (Has Many): If the related resource name is plural (e.g., comments), the service looks for items in the comments collection where the foreign key (e.g., postId) matches the current item's id.
  4. How query string filters are parsed

    main

    JSON-Server uses a specific syntax to parse query strings into filter objects. You can specify filters using two primary patterns:

    1. Colon Syntax: Use a colon (:) to separate the property path from the operator (e.g., price:gt). If no operator is provided after the colon, it defaults to eq.
    2. Underscore Syntax (Legacy/Compatibility): Use an underscore (_) to separate the property path from the operator (e.g., price_gt). This is maintained for compatibility with older versions.

    When a filter is parsed, the value is automatically coerced into its appropriate type: true becomes a boolean, false becomes a boolean, null becomes null, and numeric strings are converted to numbers. For the in operator, values are treated as a comma-separated list.

    // Colon syntax
    ?price:gt=10
    
    // Underscore syntax
    ?price_gt=10
    
    // Default equality
    ?name=typicode
    
    // 'in' operator with comma-separated values
    ?tags:in=red,blue,green
  5. Configure AppOptions for createApp

    main

    When calling createApp, you can pass an AppOptions object to customize the server behavior:

    • logger (optional, boolean): Enables or disables logging.
    • static (optional, string[]): An array of paths to additional directories to serve as static files. Paths can be absolute or relative to the current working directory (process.cwd()).
    const options: AppOptions = {
      logger: true,
      static: ['assets', '/var/www/html']
    }
  6. Paginate results

    main

    Use _page and _per_page to paginate array resources.

    • _per_page defaults to 10 if not specified.
    • Invalid values are automatically normalized to valid ranges.

    The response includes metadata about the pagination state.

    GET /posts?_page=1&_per_page=25

    Response Format:

    {
      "first": 1,
      "prev": null,
      "next": 2,
      "last": 4,
      "pages": 4,
      "items": 100,
      "data": [
        { "id": "1", "title": "...", "views": 100 }
      ]
    }
  7. Filter resources using conditions

    main

    You can filter array resources using the syntax field:operator=value.

    Supported operators:

    • (no operator) eq: equal
    • lt: less than
    • lte: less than or equal
    • gt: greater than
    • gte: greater than or equal
    • ne: not equal
    • in: included in a comma-separated list
    • contains: string contains (case-insensitive)
    • startsWith: string starts with (case-insensitive)
    • endsWith: string ends with (case-insensitive)

    You can also filter by nested properties using dot notation (e.g., author.name:eq=typicode).

    GET /posts?views:gt=100
    GET /posts?title:eq=Hello
    GET /posts?id:in=1,2,3
    GET /posts?author.name:eq=typicode
    GET /posts?title:contains=hello
    GET /posts?title:startsWith=Hello
    GET /posts?title:endsWith=world
  8. Perform complex queries with `_where`

    main

    The _where query parameter accepts a JSON object that allows for complex logical queries (like or or and) which override standard query parameters.

    GET /posts?_where={"or":[{"views":{"gt":100}},{"author":{"name":{"lt":"m"}}}]}
  9. Delete dependent resources

    main

    When deleting a resource, you can use the _dependent query parameter to also delete related resources. For example, deleting a post can automatically delete its associated comments.

    DELETE /posts/1?_dependent=comments
  10. Embed related resources

    main

    Use the _embed query parameter to include related resources in the response. For example, if posts have a relationship with comments, you can embed comments within the post object.

    GET /posts?_embed=comments
    GET /comments?_embed=post