73

I have an API reference in a Swagger file. I want to create a very simple mock server, so that when I call e.g.:

mymockurl.com/users it will return a predefined JSON (no need to connect to a database).

What's the easiest way to do this? I'm not a backend guy.

Helen
  • 58,317
  • 8
  • 161
  • 218
rafakob
  • 2,759
  • 2
  • 17
  • 29

10 Answers10

49

An easy way to create simple mock from an OpenAPI (fka. Swagger) spec without code is to use a tool call prism available at http://github.com/stoplightio/prism

This command line is all you need:

./prism run --mock --list --spec <your swagger spec file>

The mock server will return a dynamic response based on the OpenAPI spec. If examples are provided in the spec, prism will return them, if not it will generate dummy data based on the spec.

Edit (Aug 2020):

The command has changed in the latest version. The following will do:

prism mock <your spec file>

It accepts swagger and postman doc as well.

sɐunıɔןɐqɐp
  • 2,609
  • 15
  • 30
  • 36
Arnaud Lauret
  • 3,763
  • 1
  • 18
  • 26
  • 1
    The page has moved to http://stoplight.io/platform/prism/ - Also see https://github.com/stoplightio/prism – Philipp Paland Nov 16 '16 at 09:29
  • Thanks for clarifying "Open API (fka. Swagger)"! I'm a little late to this game. – Benxamin Nov 20 '17 at 21:56
  • Looks like this option "run" is outdated and no longer available in the newest version of prism. Apparently it has been replaced by "mock", but I have not found any replacement for "--list" – Tomasz Przychodzki Jun 27 '18 at 10:20
  • 7
    Just a short heads up: prism is not open source software and the license of prism itself is unclear. The MIT licensed installers are downloading a binary package of prism. – Thomas Sep 11 '18 at 09:13
  • 1
    The team added the Apache 2.0 license at the end of May 2019. As a result, the software license is no longer unclear. – maxarndt Jan 23 '20 at 11:20
  • The [prism](http://stoplight.io/platform/prism) link is invalid, **404 This page doesn't exist!** – Boris Mar 31 '20 at 14:37
  • It does not seem to support different responses based on conditions – Nikos Oct 15 '20 at 09:04
32

SwaggerHub provides a mock server for OpenAPI 2.0 and 3.0 specs. Mocking is supported on both free and paid plans.

To use the mock server, import your spec into SwaggerHub and enable "API Auto Mocking". Mock responses can be JSON, YAML and XML, and are generated based on your response schemas and the example, default and enum values defined in the schemas.

Disclosure: I work for the company that makes SwaggerHub.

Helen
  • 58,317
  • 8
  • 161
  • 218
  • 2
    Great! It does exactly what I needed! I'm marking this as an answer. The one thing I don't like is the pricing - there should be a smaller plan for freelancers who just want to have couple of private APIs. – rafakob Dec 29 '17 at 22:55
  • 1
    Can I deploy such such server locally on my network? Or it can be done only using swaggerhub.com? – Ivan Vinogradov Sep 26 '19 at 12:29
  • 2
    @IvanVinogradov SwaggerHub has both SaaS and On-Premise versions, and other answers mention mock tools that you can install and use locally. – Helen Sep 26 '19 at 12:33
  • 1
    @Helen is SwaggerHub opensource? – Max Barrass Jun 16 '20 at 03:00
  • 2
    @MaxBarrass No. – Helen Jun 16 '20 at 07:25
  • @Helen - I've defined multiple response examples but my virt server endpoint provided by the "API Auto Mocking" only ever returns the first example in the list. Is there a way to get it to randomly chose a different one each time? – John Feb 10 '21 at 12:11
  • @John currently this is [not supported](https://support.smartbear.com/swaggerhub/docs/integrations/api-auto-mocking.html#how): _"if `examples` contain multiple examples, the first example will be used"_. Please feel free to [submit a feature request](https://support.smartbear.com/swaggerhub/message/). (However, [randomized responses](https://support.smartbear.com/readyapi/docs/virtualization/configure/dispatch/index.html) are supported in our [ReadyAPI Virtualization](https://smartbear.com/product/ready-api/features/api-virtualization-features/) product if that's an option for you.) – Helen Feb 10 '21 at 12:48
15

Imposter is a A scriptable, multipurpose mock server.

Very easy to setup in a Docker environment and provides a Swagger UI to play with your mock api.

Let's see an example setup

  1. Have a swagger configuration ready in a file in the folder config/petstore.yaml

    swagger: "2.0"
    info:
    version: 1.0.0
    title: Swagger Petstore
        .
        .
        .
    

    You can copy the example swagger specification from here.

  2. Create a configuration file for Imposter in config/openapi-plugin-petstore-config.json

    {
      "plugin": "com.gatehill.imposter.plugin.openapi.OpenApiPluginImpl",
      "specFile": "petstore.yaml"
    }
    

    Name of the configuration file has to end with -config.json.

  3. Run Imposter with Docker

    Ensure that your shell is placed in the parent directory of config and run

    docker run -ti -p 8443:8443 \
    -v $(pwd)/config:/opt/imposter/config \
    outofcoffee/imposter-openapi
    
  4. Open http://localhost:8443/_spec/ to play with your Mock Server and Swagger UI

    Imposter Mock API

Fitsyu
  • 752
  • 9
  • 19
u2ix
  • 502
  • 1
  • 4
  • 12
  • 4
    Disclosure: I'm the author of the above project, Imposter. Since the original poster asked about 'the easiest way to do this', I'd also like to point you to the free hosted version of Imposter, over on https://www.remotebot.io/mocks - the hosted version doesn't require you to run anything yourself, just upload your Swagger API spec and it will create an instant mock. – outofcoffee Jun 03 '17 at 19:21
  • @outofcoffee I like imposter and find it easy to setup on my mac. just wondering , is it possible to use imposter without docker specially in windows machines. – Akash Jul 02 '19 at 20:23
  • 1
    Hi @Akash, yes - see the 'Running as a standalone Java application' section in the docs: https://github.com/outofcoffee/imposter/blob/master/docs/getting_started.md#running-as-a-standalone-java-application – outofcoffee Dec 20 '19 at 22:16
  • @outofcoffee, does it offer a mechanism to dynamically get different responses based on http return codes e.g: `200`, `404` for the same API call? – kaizenCoder May 13 '20 at 08:09
  • Hi @kaizenCoder, yes - you can control the response behaviour via scripting. This enables you to choose which status code (and thus corresponding example response) to return. You can examine various properties of the request (headers, parameters etc.) to determine if you want to return an error code or a success status code. The example in the spec for the status code you specify will be returned. Here's some information about scripting responses: https://github.com/outofcoffee/imposter/blob/master/docs/scripting.md – outofcoffee Jun 23 '20 at 22:55
13

Given the OpenAPI/Swagger spec, you can use Swagger Codegen to generate server stub in different server frameworks (e.g. Java Spring. PHP Slim, Ruby on Rails5, etc).

Here is the related documentation:

https://github.com/swagger-api/swagger-codegen/wiki/Server-stub-generator-HOWTO

UPDATE: In May 2018, about 50 top contributors of Swagger Codegen decided to fork the project to create a community-driven version called OpenAPI Generator. Please refer to the Q&A for the reasons behind the fork.

William Cheng
  • 7,639
  • 4
  • 43
  • 70
  • Will this return predefined json responses? Can you help @wing328? – elizabetht Apr 04 '17 at 15:43
  • 1
    It may depend on the generator. Please start the discussion in https://github.com/swagger-api/swagger-codegen/issues instead. – William Cheng Apr 05 '17 at 14:20
  • I opened an issue few daya ago but no response yet: https://github.com/swagger-api/swagger-codegen/issues/5310 I tried using inflector as well but no luck there. How do I get predefined json responses to be returned using swagger? The UI developer would want to try out the API and see the sample response. – elizabetht Apr 06 '17 at 15:07
4

Here is the docker container for mock api server from swagger yaml.

docker run -i \
    -p 8000:8000 \
    -v /path/to/file.yaml:/data/swagger.yaml \
    -t palo/swagger-api-mock:latest

This is internally using swagger-mock-api

arulraj.net
  • 3,579
  • 2
  • 31
  • 35
2

I docker composed Swagger Editor, Swagger UI and Swagger mock api server to handle them more easily. Check it out. There is a sample swagger spec in this so the Editor, UI and the mock API server will run without any configuration from the start. All you need to do is edit the swagger spec, save swagger.json and swagger.yaml, and restart docker.

swagger-all-in-one-docker-compose

  • Welcome to Stack Overflow! While links are great way of sharing knowledge, they won't really answer the question if they get broken in the future. Add to your answer the essential content of the link which answers the question. In case the content is too complex or too big to fit here, describe the general idea of the proposed solution. Remember to always keep a link reference to the original solution's website. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – sɐunıɔןɐqɐp Jul 27 '18 at 07:12
0

openapi-mock is a CLI wrapper for swagger-node-runner and sway specifically to start a mock server from an openapi/swagger spec file.

Alasdair McLeay
  • 2,300
  • 3
  • 22
  • 48
  • If it only worked to return example data from Swagger definition by the mock it server, or it's just me who doesn't know how to configure it... – Tomasz Przychodzki Jun 27 '18 at 14:47
0

MockLab now supports auto-generation of mock APIs from an imported Swagger definition. And you can also set it up as a webhook received in Swaggerhub so it gets updated on every save/publish:

https://www.mocklab.io/blog/mocklab-now-supports-swagger-and-swaggerhub/

Tom
  • 2,258
  • 15
  • 12
0

Mock Server project supports creating stubs based on Swagger/OpenAPI Specs.

https://www.mock-server.com/mock_server/using_openapi.html

Saikat
  • 8,190
  • 12
  • 69
  • 94
0

I created mock api server myself that can server swagger.json file. It is very easy to setup locally if you have python installed.

Have a look at this: https://github.com/bikcrum/Mock-API-server

Just use this command to serve your swagger.json file which will create API endpoints based on specification on the swagger file.

Quick and straightforward

python app.py -s /path/to/swagger.json

Extended options

usage: app.py [-h] -s SOURCE [-p PORT] [-t {swagger}] [-sc STATUS_CODE] [-r RANDOM_SEED] [-d DEFAULT_VALUE [DEFAULT_VALUE ...]]
              [-l LIST_SIZE [LIST_SIZE ...]]

Options for mock responses

Required and optional arguments:
  -h, --help            show this help message and exit

  -s SOURCE, --source SOURCE
                        (Required) API reference source file path.
  
  -p PORT, --port PORT  (Optional,default=5000) Port number the app runs on.

  -t {swagger}, --type {swagger}
                        (Optional,default='swagger') Type of API reference. Currently only supports Swagger.

  -sc STATUS_CODE, --status_code STATUS_CODE
                        (Optional,default=200) Generates responses with status code provided.

  -r RANDOM_SEED, --random_seed RANDOM_SEED
                        (Optional) Generates random responses based on seed value.

  -d DEFAULT_VALUE [DEFAULT_VALUE ...], --default_value DEFAULT_VALUE [DEFAULT_VALUE ...]
                        (Optional) Sets default values in response body. Format key=value.

  -l LIST_SIZE [LIST_SIZE ...], --list_size LIST_SIZE [LIST_SIZE ...]
                        (Optional,default=[2]) Sets default size of list in response body.

bikram
  • 3,748
  • 29
  • 39