• This repository has been archived on 20/Oct/2023
  • Stars
    star
    311
  • Rank 134,521 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

More Repositories

1

awesome-javascript-learning

A tiny list limited to the best JavaScript Learning Resources
5,295
star
2

awesome-css-learning

A tiny list limited to the best CSS Learning Resources
3,240
star
3

dave

A totally simple and very easy to configure stand alone webdav server
Go
350
star
4

Baumeister

Unmaintained – 👷 The aim of this project is to help you to build your things. From Bootstrap themes over static websites to single page applications.
SCSS
171
star
5

awesome-open-source-supporting

An awesome list about possibilities to support Open Source
115
star
6

projectforge

Java
103
star
7

cli-error-notifier

Sends native desktop notifications if CLI apps fail
JavaScript
71
star
8

projectforge-webapp

ProjectForge is a web-based solution for project management including time tracking, team-calendar, financial administration, issue management, controlling and managing work-break-down-structures (e. g. together with JIRA as issue management system).
Java
61
star
9

generator-http-fake-backend

Yeoman generator for building a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.
JavaScript
58
star
10

JiraRestClient

A simple Java Client for the JIRA Rest-API.
Java
55
star
11

generator-baumeister

Unmaintained – Yeoman Generator for »Baumeister«. The aim of this project is to help you to build your things. From Bootstrap themes over static websites to single page applications.
JavaScript
54
star
12

webengineering-2017

Source code, slides and miscellaneous stuff for the lecture Webengineering 2017 at the University of Kassel
Java
18
star
13

Merlin

Magic and customer-friendly Excel, Word and configuration acrobatics, including upload/download and templating.
Java
17
star
14

sawdust

Java module system and JUnit 5 tests
Java
15
star
15

borgbackup-butler

A client for a convenient handling of backups created by borg, such as restoring, listing etc.
JavaScript
15
star
16

check-packages

CLI tool to check your npm dependencies against a list of allowed/forbidden packages.
JavaScript
14
star
17

ConfluenceRestClient

A simple Java Client for the Confluence Rest-API.
Java
12
star
18

iFORP

Next Level HTML Prototyping -- https://prototyping4innovation.de/iforp
JavaScript
7
star
19

documentsearch

We build a document search engine with play!, elasticsearch and git. - conference repository
Scala
7
star
20

pdf-renderer

Node.js based renderer using Handlebars und JSON data to generate PDFs from HTML-Pages using wkhtmltopdf
JavaScript
6
star
21

hungry-fetch

Nomnomnom... lets you test your fetch calls.
TypeScript
6
star
22

webengineering-2019

Slides and code for the lecture Webengineering 2019 at the University of Kassel
Java
4
star
23

WebSecurity

WebSecurity Projekt.
JavaScript
4
star
24

baumeister.io

The website of Baumeister
CSS
4
star
25

labs-spring-security

Example code for blog articles about spring-security under https://labs.micromata.de/blog/tutorial-spring-security-uebersicht.html
Java
4
star
26

JUGH-2012-Adam-Bien

Java
4
star
27

paypal

Integration of PayPal in your Java application
Java
4
star
28

cloud-elastic-workloads

t+x^2 project demonstrating multiple approaches to automatically scale performance-critical application parts using cloud technologies
Java
4
star
29

mgc

Micromata Genome Commons
Java
4
star
30

tec-talk-spa-coding-samples

This repository contains the coding samples for the tec talk »Single Page Apps - A Framework Agnostic Approach« by René Viering
CSS
4
star
31

projectforge-excel

Excel export package (convenient usage of POI) for exporting MS-Excel sheet with a few lines of code or modifiing existing MS-Excel sheets.
Java
4
star
32

open-data-codefest

Ergebnisse des Open Data Codefest
Jupyter Notebook
3
star
33

ProFi-Pattern-Library

CSS
3
star
34

webengineering-2015-ss

Lecture material for Webengineering at the University of Kassel
3
star
35

generator-bootstrap-kickstart

[deprecated] Check the successor Baumeister instead.
JavaScript
3
star
36

xjcpluginjavaapiforkml

XJC Plugin to generate the Java API for KML.
HTML
3
star
37

es-log4j2

Log4j2-NoSQL-Appender for elasticsearch
Java
3
star
38

projectforge-continuous-db

Supports programmatically creation and updates of data-bases for continuous delivery independent of the data-base vendor. SQL-Scripts may be created manually or automatically by parsing JPA annotations with a few lines of code.
Java
3
star
39

projectforge-sync-adapter

Java
2
star
40

projectforge-common

Common used classes (by web app, standalone etc.).
Java
2
star
41

projectforge-webserver

Start helper for jetty.
Java
2
star
42

webengineering-2015-ss-demo

Source code of the live-coding demo for the lecture Webengineering.
Java
2
star
43

projectforge-jax-rs

Java API for RESTful Web Services
Java
2
star
44

spring-slim-docker-images

Example repository for slim spring docker images
Dockerfile
2
star
45

baumeister-media

Baumeister logo and artwork
PostScript
2
star
46

tpsb

TestBuilder Framework
Java
1
star
47

bootstrap-kickstart

[deprecated] Check the successor Baumeister instead.
CSS
1
star
48

raktajino

Raktajino - JUnit Extensions, served steamed or iced
Java
1
star
49

labs-website

Home of Micromata Open Source Content.
SCSS
1
star
50

eslint-config-baumeister

This package provides Baumeisters ESLint settings as an extensible shared config.
JavaScript
1
star