Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.

Overview

GitHub version Build Status Coverage Status Dependency Status devDependency Status Unicorn

http-fake-backend

Build a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.

It actually can serve the content of other file types as well as sending the files itself as response.

Comes as a Node.js server. Useful for mocking, testing and developing independent of the »real« backend.

Example

Let’s say you need an endpoint like http://localhost:8081/api/example which should return:

{
  "response": "Yeah"
}

It’s a matter of seconds to create this endpoint with help of this little hapi server.

It might take a few seconds longer as setting up the well-made JSON Server but it’s way more flexible.

Requirements

  • Node.js (v6.0.0 or greater)

Install

git clone https://github.com/micromata/http-fake-backend.git
npm install

Or with help of Yeoman

npm install -g yo
npm install -g generator-http-fake-backend

This comes in handy, because the Yeoman generator has a sub-generator to setup endpoints of your fake backend very convenient. See https://github.com/micromata/generator-http-fake-backend.

Default Address

The server runs at http://localhost:8081/ providing a page with links to all existing API endpoints.

Start the server

There are the following two options.

During development

npm run start:dev

This way the server uses nodemon to restart itself on changes.

Later (eg. for tests in CI)

npm start

Just starts the server via node.

Configure endpoints

Each endpoint needs a configuration file in /server/api/ to define routes, http method and the response.

Example configurations

Simple Example

/server/api/simpleExample.js:

module.exports = SetupEndpoint({
    name: 'simpleExample',
    urls: [{
        requests: [
            { response: '/response-files/simpleExample.json' }
        ]
    }]
});

Advanced Example

/server/api/anotherExample.js:

module.exports = SetupEndpoint({
    name: 'anotherExample',
    urls: [{
        params: '/read',
        requests: [{
            method: 'GET',
            response: '/response-files/anotherExample.json'
        }]
    }, {
        params: '/update/{id}',
        requests: [{
            method: ['PUT', 'PATCH'],
            response: {
                success: true
            }
        }, {
            method: 'DELETE',
            response: {
                deleted: true
            }
        }]
    }, ]
});

Serving different content types

/server/api/fileTypes.js:

module.exports = SetupEndpoint({
    name: 'fileTypes',
    urls: [{
        params: '/json',
        requests: [{
            response: '/response-files/simpleExample.json'
        }]
    }, {
        params: '/text',
        requests: [{
            response: '/response-files/example.txt',
            mimeType: 'text/plain'
        }]
    }, {
        params: '/html',
        requests: [{
            response: '/response-files/example.html',
            mimeType: 'text/html'
        }]
    }, {
        params: '/pdf',
        requests: [{
            response: '/response-files/example.pdf',
            sendFile: true
        }]
    }]
});

Faking HTTP errors and status code

/server/api/fakingStatusCodes.js:

module.exports = SetupEndpoint({
    name: 'statusCodes',
    urls: [
        {
            params: '/boomError',
            requests: [{
                // Returns a 402 status code + error message provided by boom:
                // {
                //   "error" : "Payment Required",
                //   "message" : "Payment Required",
                //   "statusCode" : 402
                // }
                statusCode: 402
            }]
        },
        {
            params: '/customError',
            requests: [{
                // Returns a HTTP status code 406 and a self defined response:
                response: { error: true },
                statusCode: 406
            }]
        },
        {
            params: '/regularResponse',
            requests: [{
                // Returns a 401 error provided by boom
                // as defined on endpoint level
                response: '/response-files/anotherExample.json'
            }]
        }
    ],
    statusCode: 401
});

The configuration object in Detail:

  • name
    • Is used to set the endpoint.
  • urls
    • You need to add at least one url object.
  • urls.params
    • Optional
    • URL path parameters with fixed and/or variable path segments.
    • Example:
      • params: '/update/{id}'
    • See hapi docs. For example regarding optional path parameters.
  • urls.requests
    • You need to add at least one request object.
    • Multiple request objects are needed in case you like to serve different responses via different HTTP methods with the same URL.
  • urls.requests.method
    • optional. Uses GET when not defined.
    • string, or array of strings.
    • is used to define the http method(s) to which the endpoint will listen.
  • urls.requests.response
    • Could be a string pointing to a file:
      • response: '/response-files/articles.json'
    • Or just a JavaScript object:
      • response: { success: true }
  • urls.requests.mimeType
    • Optional (string). Defaults to application/json.
    • Is used to set the content-type response header.
  • urls.requests.sendFile
    • Optional (boolean). Defaults to false.
    • Sends the file as response instead of returning the file content.
  • urls.requests.statusCode
    • Optional (boolean). Defaults to 200
    • The HTTP status code of the response.
    • Will return:
      • a status code with a self defined response if you provide a response property
      • a status code with a predefined error object provided by boom if you dont provide a response property for that request.
  • statusCode
    • Optional
    • Every subroute of this endpoint will return a HTTP error with the given status code provided by boom.

Configure server

The main config is handled via a file named .env with the following content:

# NODE_ENV
# Could be either `development` or `production`
NODE_ENV=development

# Port of the Server
SERVER_PORT=8081

# Port for running the tests
TEST_PORT=9090

# URL Prefix for the endpoints
# eg. http://localhost:8081/api/foo
API_PREFIX=/api

# Custom response header
#CUSTOM_HEADER_NAME=Authorization
#CUSTOM_HEADER_VALUE=Bearer eyJhbGciOiJIUzUxMiJ9

Related

  • Yeoman Generator – Easily generate your fake backend and use sub-generators to setup endpoints like

License

Please be aware of the licenses of the components we use in this project. Everything else that has been developed by the contributions to this project is under MIT License.

Comments
  • Error: New route X conflicts with existing Y

    Error: New route X conflicts with existing Y

    {
            {
                params: '/{id}/note/{noteId}',
                method: 'PUT'
            },
            {
                params: '/{id}/note/{noteId}',
                method: 'PATCH'
            }
    }
    

    This should work since there are different methods to the same endpoint, but it fails with the following message: Error: New route /api/salesItem/{id}/note/{noteId} conflicts with existing /api/salesItem/{id}/note/{noteId}

    opened by krnlde 9
  • Feat: Add support for plain text response as alternative to JSON

    Feat: Add support for plain text response as alternative to JSON

    Hey @mischah, Very promising work! I landed here once the json-server has some limitations.

    What I would like to know is how can I return a simple text in some cases.

    E.g When I make a PUT request to /api/simpleExample/update/1 to get the text DONE

    module.exports = SetupEndpoint({
        name: 'simpleExample',
        urls: [{
            requests: [...]
        },
        {
            params: '/update/{id}',
            requests: [{
                method: ['PUT', 'PATCH'],
                response: 'DONE'
            }, {
                method: 'DELETE',
                response: 'DELETED'
            }]
        }]
    });
    

    Thank you

    enhancement 
    opened by stelioschar 3
  • Using Yarn

    Using Yarn

    • Update dependencies
    • Add yarn lock file
    • Use Yarn on Travis
      • Right now I have to install yarn via npm so we dont have a huge perfomance win comparing yarn install with npm install.
      • Plus I still have to call the npm scripts via npm because yarn run is broken in the current release.
      • But we have a reproducible installation thanks to the lock file provided by Yarn. :heart_eyes:
      • Plus Yarn can handle optional dependencies like fsevents :heart_eyes:
    enhancement 
    opened by mischah 3
  • Only getting response for GET Method

    Only getting response for GET Method

    I am not able to get a response for a PUT method.I get the below {"statusCode":405,"error":"Method Not Allowed","message":"Method Not Allowed"} I get this for the default put example provided too.Could you please help me out with this.I might be missing something.

    opened by kaustavbasu075 2
  • Remove hint for using Yarn

    Remove hint for using Yarn

    In my opinion this hint is deprecated with npm 5.3.X. My Shell told me this after an install with npm: "added 567 packages in 9.595s"

    So i think you can use Yarn but there is noch downside with npm anymore.

    opened by Paquan 2
  • [Snyk Update] New fixes for 4 vulnerable dependency paths

    [Snyk Update] New fixes for 4 vulnerable dependency paths

    This project has vulnerabilities that could not be fixed, or were patched when no upgrade was available. Good news, new upgrades or patches have now been published! This pull request fixes vulnerable dependencies you couldn’t previously address.

    The PR includes:

    • Changes to package.json to upgrade the vulnerable dependencies to a fixed version.

    Vulnerabilities that will be fixed

    With an upgrade:

    You can read more about Snyk's upgrade and patch logic in Snyk's documentation.

    Note that this pull request only addresses vulnerabilities that previously had no fixes. See the Snyk test report to review and remediate the full list of vulnerable dependencies.

    Check the changes in this PR to ensure they won't cause issues with your project.

    Stay secure, The Snyk team

    opened by snyk-bot 1
  • Cannot serve files (png)

    Cannot serve files (png)

    'use strict';
    
    const SetupEndpoint = require('./setup/setup.js');
    
    module.exports = SetupEndpoint({
        name: 'attachment',
        urls: [{
                       params: '/{file}',
                       requests: [{
                           sendFile: true,
                           mimeType: 'application/pdf',
                           //response: '/attachments/1.png',
    
                           response: '/attachments/test.pdf'
                       }]
                   }
                   ]
    });
    
    

    I get the error message:

    2018-02-06/16:40:42.573, [response] http://localhost:8081: get /api/app/v6/attachment/test.pdf {} 500 (51ms)
    2018-02-06/16:40:44.721, [log,connection,client,error] message: Parse Error, stack: Error: Parse Error
        at Error (native)
    2018-02-06/16:40:44.728, [log,info] data: Received payload:null
    Debug: internal, implementation, error 
        /project/attachments/test.pdf:1
    (function (exports, require, module, __filename, __dirname) { %PDF-1.3
                                                                  ^
    
    SyntaxError: Unexpected token %
        at createScript (vm.js:56:10)
        at Object.runInThisContext (vm.js:97:10)
        at Module._compile (module.js:542:28)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Module.require (module.js:497:17)
        at require (internal/module.js:20:19)
        at handler (/project/server/api/setup/setup.js:40:44)
    2018-02-06/16:40:44.724, [response] http://localhost:8081: get /api/app/v6/attachment/test.pdf {} 500 (25ms)
    
    
    opened by schmaluk 1
  • Adjust tooling

    Adjust tooling

    Setup npm scripts for automatic versioning and CHANGELOG generation via Standard Version

    Just like we did we did here: https://github.com/micromata/generator-baumeister/blob/master/package.json#L24-L27

    enhancement 
    opened by mischah 1
  • library updates + appropriate code changes

    library updates + appropriate code changes

    fixes https://github.com/micromata/http-fake-backend/issues/23

    Note:

    • Tests had 100% coverage before. Now we have a coverage of 98.36% (6/365). Due to lack of time I won't be able to fix this soon.
    • $meta were not allowed anymore as manifest server property so it were simply deleted + the appropriate test were removed
    opened by mppperez 0
  • POST not working with node 16 / npm 8

    POST not working with node 16 / npm 8

    Sending POST requests to the server is not working while using Node v16.14.0 and npm 8.3.2 but it works using node v14.19.0 npm v6.14.16.

    Executing POST requests via our app or curl resulted in waiting for the response until it timed out. The server logs already printed that the response were written but it actually never were received. Restarting the server with node v14 and npm v6 made it working again.

    Solution: updating all hapi libraries and making the appropriate changes. PR incoming.

    opened by mppperez 0
  • Does this support POST?

    Does this support POST?

    Hello, does this support POST?

    module.exports = SetupEndpoint({ name: 'anotherExample', urls: [{ params: '/write', requests: [{ method: 'POST', response: '/response-files/anotherExample.json', requestData: ?? }] }] });

    opened by merqrial 2
  • Response function instead of static data

    Response function instead of static data

    Looking at Hapi.js, it looks like you can supply a function as a handler so you can take incoming path params, etc and supply a dynamic response. Why does this not seem possible with http-fake-backend? It seems like this would be like 1 line of code in supportedMethod.js to make this work.

    Example usage: https://hapijs.com/api#path-parameters

    opened by zlanich 2
  • feature: Make it possible to use HTTPS

    feature: Make it possible to use HTTPS

    Dear,

    Please help/show me how to add more configuration in order to run this server under Https with SSL I am using your project, but we need to switch it to HTTPS rather than current normal HTTP.

    Best regards, Quang Nguyen [email protected]

    enhancement 
    opened by dqvn 3
  • feature: Support for query parameters

    feature: Support for query parameters

    Hi. Thows error when url like this

    module.exports = SetupEndpoint({
        name: 'v1',
        urls: [{
            params: '/read?cmd=on-enter&pid=1414-414-567-3636',
            requests: [{
                method: 'GET',
                response: '/json-templates/anotherExample.json'
            }]
        }]
        }]
    });
    
    enhancement help wanted 
    opened by boochamoocha 8
Releases(4.1.0)
  • 4.1.0(Feb 22, 2018)

  • 4.0.3(Feb 19, 2018)

  • 4.0.2(Dec 6, 2017)

    Bug Fixes

    • update minimum node version in package.json (131d0ab)

    Change engines.node to >=6.0.0 to reflect the minimum node version which is needed since http-fake-backend 4.0.0.

    Source code(tar.gz)
    Source code(zip)
  • 4.0.1(Dec 4, 2017)

  • 4.0.0(Dec 4, 2017)

    Bug Fixes

    • dependencies: Apply changes of boom update (a17f805)
    • dependencies: Update dependencies (ab5974a)
    • dependencies: Update dependencies (f362c9c)
    • update dependencies (bbd445b)

    Code Refactoring

    • Refactor existing codebase (3751899)

    Documentation

    • Update required minimum Node version in readme (e1c549b)

    Features

    • Add support for other response content-types (c9a7d12), closes #7
    • Add support for sending files as response (70d535f), closes #11

    BREAKING CHANGES

    • The transitive dependency [email protected] needs Node version ">=6".

    • The setup.js is divided to multiple files. Therefore you need to change the import of the setup in your endpoint files like the following:

      // before
      const SetupEndpoint = require('./setup/setup.js');
      
      // now
      const SetupEndpoint = require('./setup/index.js');
      
      // or:
      const SetupEndpoint = require('./setup/');
      

    See all changes between 3.2.4 and 4.0.0

    Source code(tar.gz)
    Source code(zip)
  • v3.2.4(Apr 1, 2017)

    Basically just updated dependencies 📦

    Changes

    • dca6d59 Update Yarn lock file
    • 5cab43c Remove Node 5 from travis config
    • 908721f Update dependencies
    Source code(tar.gz)
    Source code(zip)
  • v3.2.3(Mar 9, 2017)

  • v3.2.2(Dec 19, 2016)

    Basically just updated dependencies 📦

    Changes

    • 8a431041 Remove Snyk and update dependencies
    • ba9e22a6 Setup snyk
    • e21d842f Update dependencies
    Source code(tar.gz)
    Source code(zip)
  • v3.2.1(Nov 27, 2016)

    Just updated dependencies and did some repo/tooling maintenance :nail_care:

    Changes

    • 63c572e5 Update dependencies
    • 940746db Fix reporting to coveralls
    • 745131ae Simplify travis config (#3)
    • 30e98187 Add Code Climate batch
    • b59ee275 Code Climate setup
    • 4702c962 Readme tweaks
    • c6048daa Run npm scripts with Yarn
    • a4462284 Fix italic emoji in README
    Source code(tar.gz)
    Source code(zip)
  • 3.2.0(Oct 13, 2016)

    Changes

    • 2e658aee Add note about Yarn into the readme
    • 91846448 Use Yarn on Travis
    • f0856f82 Add yarn lock file
    • a83d5a87 Update dependencies
    • 67775831 Rename sublime settings file

    New Feature: Reproducible installations

    Thanks to the lock file provided by Yarn. That’s it. Not sure about tagging this as feature release.

    Keep in mind that you of course still can install with npm 💖

    Source code(tar.gz)
    Source code(zip)
  • 3.1.0(Sep 27, 2016)

    Changes

    • ce7b6bef Update docs and example
    • a42758f5 Feature: Improve fakability of http status codes
    • 25ba9d60 Rename existing examples
    • b07bc61d Update and pin dependencies

    New Feature: Improve fakability of HTTP status codes

    You now can define different status codes on request level in addition to defining errors on endpoint level.

    So different subroutes of one endpoint can return different HTTP status codes. Plus you can choose between:

    • a status code with a self defined response
    • a status code with a predefined error object provided by boom

    Example

    const SetupEndpoint = require('./setup/setup.js');
    
    module.exports = SetupEndpoint({
        name: 'statusCodes',
        urls: [
            {
                params: '/boomError',
                requests: [{
                    // Returns a 402 status code + error message provided by boom:
                    // {
                    //   "error" : "Payment Required",
                    //   "statusCode" : 402
                    // }
                    statusCode: 402
                }]
            },
            {
                params: '/customError',
                requests: [{
                    // Returns a HTTP status code 406 and a self defined response:
                    response: { error: true },
                    statusCode: 406
                }]
            },
            {
                params: '/regularResponse',
                requests: [{
                    // Returns a 401 error provided by boom
                    // as defined on endpoint level
                    response: '/json-templates/anotherExample.json'
                }]
            }
        ],
        statusCode: 401
    });
    
    Source code(tar.gz)
    Source code(zip)
  • 3.0.7(Sep 17, 2016)

  • 3.0.6(Aug 27, 2016)

  • 3.0.5(Jun 19, 2016)

  • 3.0.4(Jun 2, 2016)

  • 3.0.3(May 7, 2016)

  • 3.0.2(May 4, 2016)

    Changes

    • 88810c66 Adapt breaking changes from good 7.0.0
    • 320ff17f Add Node.js v6 to travis config
    • 2a0100e5 Update dependencies
    • c99eb5a2 Update README
    Source code(tar.gz)
    Source code(zip)
  • 3.0.1(Mar 20, 2016)

  • 3.0.0(Mar 13, 2016)

    Changes

    • c3b6d11b Feature: Different methods on the same route
      • It's also possible to return different responses for those different methods. Closes #1

    Breaking change because the configuration object changed again. See README.

    Source code(tar.gz)
    Source code(zip)
  • 2.0.1(Mar 10, 2016)

  • 2.0.0(Mar 10, 2016)

    Changes

    • 081ec67e Feature: Configure URL prefix for the endpoints via .env
    • 4c5c3b1e Bugfix: Use ports defined in .env
    • 9547a6cc Update description in package.json
    • 2317603a Feature: Define response as JavaScript object
      • You can now choose for each URL if the response should be defined via a JSON template file or a JavaScript object.
    • 0646b466 Fix typo
    • ab285967 Feature: Reduce work when setting up new endpoints
      • With this change you don’t need to add an endpoint plugin to the manifest.js
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Mar 5, 2016)

Owner
Micromata GmbH
Micromata GmbH
Simple, configurable part mock part proxy

Moxy Simple, configurable mock / proxy server. Table of Contents Quick start Programatic CLI Docker Docker compose Usage Programatic Via HTTP requests

Acrontum GmbH 7 Aug 12, 2022
Get a full fake REST API with zero coding in less than 30 seconds (seriously)

JSON Server Get a full fake REST API with zero coding in less than 30 seconds (seriously) Created with <3 for front-end developers who need a quick ba

null 64.9k Jan 3, 2023
HTTP Client for Visual Studio Code to POST JSON, XML, image, ... files to REST APIs

friflo POST Goal Main goal of this extension is storing all HTTP request & response data automatically as files in a VSCode workspace. This ensures th

Ullrich Praetz 2 Nov 18, 2021
A proxy web app that serves ABC iView content outside of the iView webplayer, avoiding intrusive data harvesting.

iview-proxy A proxy web app that serves ABC iView content outside of the iView webplayer, avoiding intrusive data harvesting. There's also a cool Andr

The OpenGov Australia Project 11 Jul 16, 2022
Download and extract files

download Download and extract files See download-cli for the command-line version. Install $ npm install

Kevin Mårtensson 1.2k Dec 21, 2022
Bearer provides all of the tools to build, run and manage API integrations.

Bearer - The API Integration Framework Bearer provides all of the tools to build, run and manage API Learn more Archive Status Bearer JS has been arch

Bearer.sh 22 Oct 31, 2022
A docker image to build a SQS queue listener. Written in TypeScript, made to use with docker.

sqs-request A docker image to build a SQS queue listener. Written in TypeScript, made to use with docker. SQS queue processor with node, ts-squiss, wh

Marcus Yoda 3 Jan 20, 2022
A window.fetch JavaScript polyfill.

window.fetch polyfill The fetch() function is a Promise-based mechanism for programmatically making web requests in the browser. This project is a pol

GitHub 25.6k Jan 4, 2023
A JavaScript, zero-dependency, super small version of IP2Location LITE country lookups.

ip3country This is a zero-dependency, super small, IP address to 2-letter country code lookup library. There are already several libraries available,

Statsig 34 Dec 14, 2022
A server side agnostic way to stream JavaScript.

JS in JSN A server side agnostic way to stream JavaScript, ideal for: inline hydration network free ad-hoc dependencies bootstrap on demand libraries

Andrea Giammarchi 26 Nov 21, 2022
catbot-9000 is a javascript market-loser bot running on node.js.

catbot-9000 catbot-9000 is a Chia bot framework running on node.js. It was used during the CATMOS launch event on Hashgreen. If you are looking for th

null 9 Nov 16, 2022
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
This package enables you to define your routes using the flat-routes convention.

Remix Flat Routes This package enables you to define your routes using the flat-routes convention. This is based on the gist by Ryan Florence ?? Insta

Kiliman 180 Jan 3, 2023
An isomorphic and configurable javascript utility for objects deep cloning that supports circular references.

omniclone An isomorphic and configurable javascript function for object deep cloning. omniclone(source [, config, [, visitor]]); Example: const obj =

Andrea Simone Costa 184 May 5, 2022
Generate deterministic fake values: The same input will always generate the same fake-output.

import { copycat } from '@snaplet/copycat' copycat.email('foo') // => '[email protected]' copycat.email('bar') // => 'Thurman.Schowalter668@

Snaplet 201 Dec 30, 2022
JSON Hero is an open-source, beautiful JSON explorer for the web that lets you browse, search and navigate your JSON files at speed. 🚀

JSON Hero makes reading and understand JSON files easy by giving you a clean and beautiful UI packed with extra features.

JSON Hero 7.2k Jan 9, 2023
Json-parser - A parser for json-objects without dependencies

Json Parser This is a experimental tool that I create for educational purposes, it's based in the jq works With this tool you can parse json-like stri

Gabriel Guerra 1 Jan 3, 2022
SafeCycle—a tool that keeps cyclists safe. Gone are days of weaving through busy city streets, SafeCycle finds all the bike routes for you to ensure a smooth ride wherever you want to go.

Inspiration Biking—an everyday form of travel for students and professionals across the globe. On-campus, back home, and with the people that we know

Ryan Hu 2 May 2, 2022
simple PWA catalogue with vanilla javascript and json-server as a fake server

simple PWA catalogue with vanilla javascript and json-server as a fake server

bagher musavi 2 Mar 12, 2022
generate pages from markdown files with dynamic routes, 0 effort, 0 boilerplate.

next-markdown Markdown Pages for Next.js Dynamic Routes. Blog Aware. Design Your Layout Made for people having a nextjs project in ❤️ with markdown wh

François Rouault 105 Oct 11, 2022