A tiny JSON rule based API Mocker

API Mocker

A tiny JSON rule based API mocker.

The API Mocker intends to simulate an API behavior, supported by a group of rules written as a JSON file structure.

Dependencies

go 1.17+

Running

  • Clone this project
  • Prepare your rule file
  • from the project folder run go run . -rules=my_custom_rules.json

The mock runs on localhost:8000 by default. These attributes can be changed by using -host and -port flags.

Rule file

The rule file follows a JSON structure with the following minimum fields:

{
  "rules": [
    {
      "endpoint": "/api/auth",
      "method": "GET",
      "items": [
        {
          "response": {
            "status": 200,
            "body": ""
          }
        }
      ]
    }
  ]
}

where:

  • endpoint: (mandatory) an expression path to be included in the url routes. Follows go HttpRouter Lib schema
  • method: (mandatory) any http method (GET, POST, PUT, PATCH, DELETE, OPTIONS).
  • items: (mandatory) an array of rule items where each item is composed by:
    • query: (optional) an expression to be match against the URL query, if it has one. If not provided, any query will be accepted.
    • body: (optional) a regex expression to match against the request body. If not provided, any body will be accepted.
    • counter: (optional) counter matches the number of calls a request should match (starting from zero). If not provided the matching request will return every time.
    • response: (mandatory) a structure containing the response to be sent back if the request rules above match, where:
      • status: (mandatory) a HTTP code
      • delay: (optional) delay (in ms) to take before sending the response
      • headers: (optional) an array containing a "key:value" list of headers to be sent on the response
      • body: (optional) a string with the response, with optional dynamic parsable rules based on go gjson lib

Rules by example

  • A GET method where the query match an specific value
      {
        "endpoint": "/api/auth/:code",
        "method": "GET",
        "items": [
          {
            "query": "1234",
            "response": {
              "status": 200
            }
          }
        ]
      }
  • A GET method simulating an error, after waiting for 5 seconds
      {
        "endpoint": "/api/auth",
        "method": "GET",
        "items": [
          {
            "response": {
              "status": 413,
              "delay": 5000
            }
          }
        ]
      }
  • A POST method where the body match specific content
      {
        "endpoint": "/api/auth",
        "method": "POST",
        "items": [
          {
            "body": "\"name\":",
            "response": {
              "status": 200
            }
          }
        ]
      }
  • A POST method where the body match multiple content, in this case must have user and password words
      {
        "endpoint": "/api/auth",
        "method": "POST",
        "items": [
          {
            "body": ".*user.*password",
            "response": {
              "status": 200
            }
          }
        ]
      }
  • A POST method simulating error returning with json
      {
        "endpoint": "/api/auth",
        "method": "POST",
        "items": [
          {
            "response": {
              "status": 417,
              "headers": [
                "Content-Type: application/json"
              ],
              "body": "{\"message\": \"Failed to respond\"}"
            }
          }
        ]
      }
  • A POST method with dynamic answer, parsing 1st element from request body. Dynamic parsing based on go gjson lib
      {
        "endpoint": "/api/auth",
        "method": "POST",
        "items": [
          {
            "response": {
              "status": 417,
              "headers": [
                "Content-Type: application/json"
              ],
              "body": "{\"requested-hash\": \"{{sha256|@keys|0}}\"}"
            }
          }
        ]
      }
  • A POST method where the body match specific content with counter. In the first call it returns 200, second matching call 400 and all subsequent call 202 with a json body.
      {
        "endpoint": "/api/auth",
        "method": "POST",
        "items": [
          {
            "counter": 0,
            "body": ".*user",
            "response": {
              "status": 200
            }
          },
          {
            "counter": 1,
            "body": ".*user",
            "response": {
              "status": 400
            }
          },
          {
            "body": ".*user",
            "response": {
              "status": 202,
              "headers": [
                "Content-Type: application/json"
              ],
              "body": "{\"message\": \"ok\"}"
            }
          }
        ]
      }

Docker

Starting the api mocker on docker is very simple:

docker build -t api-mocker:latest .
docker run -v "/$(pwd)/rules:/rules" -p 8000:8000 api-mocker:latest  -rules=rules/test-rule.json

note that you always need to define the volume and path for the rules.

It is also possible to use it directly from Docker Hub: docker pull nordsec/api-mocker

Via docker-compose

Example docker-compose.yml:

version: "3.7"

services:
  api-mocker:
    build:
      context: .
      target: api-mocker
    command: ["-rules", "rules/test-rule.json"]
    ports:
      - "8000:8000"
    volumes:
      - ./rules:/rules

run docker-compose up wait for it to initialize completely, and visit http://localhost:8000/any-path-defined-on-rules-file

Owner
Nord Security
Nord Security is one of the leaders in providing digital security and privacy solutions for individuals and businesses
Nord Security
Similar Resources

Simple-Weather-API - Simple weather api app created using golang and Open Weather API key

Simple-Weather-API - Simple weather api app created using golang and Open Weather API key

Simple Weather API Simple weather api app created using golang and Open Weather

Feb 6, 2022

The Fabric Token SDK is a set of API and services that lets developers create token-based distributed application on Hyperledger Fabric.

The Fabric Token SDK is a set of API and services that let developers create token-based distributed application on Hyperledger Fabric.

Dec 14, 2022

A REST API microservices-based Twitter Clone server.

Simple API Twitter Clone A REST API microservices-based project to fetch, edit, post, and delete tweets. API documentation The API documentation is bu

May 13, 2022

Us-api: a simple service that returns the US state code based on the state

us-api us-api is a simple service that returns the US state code based on the state. It does not support creating, updating nor deleting data. Local D

Dec 13, 2021

API-HTTP service for wav-file synthesis based on sound library (morphemes)

Сервис для генерации аудио-файлов по заданной последовательности звуков из библиотеки. Предоставляет HTTP-API для передачи последовательности для гене

Jan 9, 2022

Backgammon Web API. Sophisticed neural net based multi-ply evalution engine for Backgammon moves

Backgammon Web API. Sophisticed neural net based multi-ply evalution engine for Backgammon moves.

Dec 25, 2022

Go library to interface with Solana JSON RPC and WebSocket interfaces

Go library to interface with Solana JSON RPC and WebSocket interfaces

Solana SDK library for Go Go library to interface with Solana JSON RPC and WebSocket interfaces. Clients for Solana native programs, Solana Program Li

Mar 2, 2022

Search and output the value of JSON by it's path.

golang-cli Get the value of a JSON element via it's path name. Usage ======= jutil ======= Usage: jutil [-p path] [-v] Options: -p string

Dec 19, 2021

Go library for accessing the MyAnimeList API: http://myanimelist.net/modules.php?go=api

go-myanimelist go-myanimelist is a Go client library for accessing the MyAnimeList API. Project Status The MyAnimeList API has been stable for years a

Sep 28, 2022
An API for generating JSON based STIX objects and TAXII messages with the Go

libstix2 an API for generating JSON based STIX objects and TAXII messages with the Go (Golang) programming language. Please see the examples directory and the README files in each of the sub packages for more information. This API is built to support STIX 2.x and TAXII 2.x.

Dec 21, 2021
Instances-api - A JSON API to fetch Piped instances

Instances-Api Hosting it yourself docker-compose up -d You can now access the AP

Dec 27, 2022
A serverless teeny-tiny version of Diomedes which sends alerts to Telegram. Written in Go.
A serverless teeny-tiny version of Diomedes which sends alerts to Telegram. Written in Go.

diomedes-search Get a notification on Telegram whenever your movie opens bookings in a theater of your choice. Pre-requisites Install AWS CLI (v2) by

Oct 11, 2022
Tiny go package for fetching high and low value of a stock for any given period range using kite connect historical data APIs.

Tiny go package for fetching high and low value of stock for any given period range using Kite connect Historical data APIs.

Apr 27, 2022
An unofficial API based on Hasura API Reference.

An unofficial API based on Hasura API Reference.

Apr 14, 2022
Golang client for ethereum json rpc api

Ethrpc Golang client for ethereum JSON RPC API. web3_clientVersion web3_sha3 net_version net_peerCount net_listening eth_protocolVersion eth_syncing e

Jan 7, 2023
Light JSON API for storing user ratings of NASA's Astronomy Picture of the Day (APOD).
Light JSON API for storing user ratings of NASA's Astronomy Picture of the Day (APOD).

nasa-apod-api-go Light JSON API for storing user ratings of NASA's Astronomy Picture of the Day (APOD). To run this server you must have access to a N

Oct 26, 2021
I try to make a Restfull-API with golang and interaction with json.file

{ "users": [ { "name": "Elliot", "type": "Reader", "age": 23, "social": { "facebook": "https://facebook.com",

Jan 5, 2022
Convert IBM stanza-style files to json and publish as an API

stanza_to_json Convert IBM stanza-style files to json and publish as an API Background IBM Stanza files have been extended to be used in other ways, b

Feb 2, 2022
JSON API for a random meme scraped from reddit.

JSON API for a random meme scraped from reddit.

Jan 2, 2023