Code Monkey home page Code Monkey logo

prism's Introduction

Prism - API Mock Servers and Contract Testing

CircleCI NPM Downloads Stoplight Forest

Prism Overview

Prism is a set of packages for API mocking and contract testing with OpenAPI v2 (formerly known as Swagger) and OpenAPI v3.x.

Prism provides:

  • Mock Servers: Life-like mock servers from any API specification document.
  • Validation Proxy: Contract Testing for API consumers and developers.
  • Comprehensive API Specification Support: OpenAPI v3.1, OpenAPI v3.0, OpenAPI v2.0 (formerly Swagger) and Postman Collections.

Ways to Use Prism

Hosted Prism

Stoplight provides hosted mock servers for convenience so that API consumers can experiment with an API without the need for backend code.

Use one of these options for instant, hosted mock servers:

  • Stoplight Platform: Collaborative API Design Platform for designing, developing and documenting APIs with hosted mocking powered by Prism.
  • Stoplight Studio: Free visual OpenAPI designer that comes integrated with mocking powered by Prism.

Learn more in the hosted Prism documentation.

Self-hosted Prism

Prism is an open-source HTTP server run from the command-line. It provides mocking, request validation, and content negotiation. Use it standalone tool or in continuous integration.

Demo of Prism Mock Server being called with curl from the CLI

Installation and Usage

This information refers to Open Source Prism 3.x, which is the current version most likely you will use. If you're looking for the 2.x version, look at the 2.x branch

Install Self-hosted Prism

Prism requires

npm install -g @stoplight/prism-cli

# OR

yarn global add @stoplight/prism-cli

For more installation options, see our installation documentation.

Mocking

Prism can help you create a fake "mock" based off an OpenAPI document, which helps people see how your API will work before you even have it built. Run it locally with the prism mock command to run your API on a HTTP server you can interact with.

prism mock https://raw.githack.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml

Learn more about how the mock server works.

Validation Proxy

Prism can help you check for discrepencies between your API implementation and the OpenAPI document that describes, letting you funnel HTTP traffic through it with the prism proxy command.

prism proxy examples/petstore.oas2.yaml https://petstore.swagger.io/v2

Learn more about how the validation proxy works.

πŸ“– Documentation and Community

❓ FAQs

Cannot access mock server when using Docker?

Prism uses localhost by default, which usually means 127.0.0.1. When using docker the mock server will be unreachable outside of the container unless you run the mock command with -h 0.0.0.0.

Why am I getting 404 errors when I include my basePath?

OpenAPI v2.0 had a concept called "basePath", which was essentially part of the HTTP path the stuff after host name and protocol, and before query string. Unlike the paths in your paths object, this basePath was applied to every single URL, so Prism v2.x used to do the same. In OpenAPI v3.0 they merged the basePath concept in with the server.url, and Prism v3 has done the same.

We treat OAS2 host + basePath the same as OAS3 server.url, so we do not require them to go in the URL. If you have a base path of api/v1 and your path is defined as hello, then a request to http://localhost:4010/hello would work, but http://localhost:4010/api/v1/hello will fail. This confuses some, but the other way was confusing to others. Check the default output of Prism CLI to see what URLs you have available.

🚧 Roadmap

Submit your ideas for new functionality on the Stoplight Roadmap.

🏁 Help Others Utilize Prism

If you're using Prism for an interesting use case, contact us for a case study. We'll add it to a list here. Spread the goodness πŸŽ‰

πŸ‘ Contributing

If you are interested in contributing to Prism itself, check out our contributing docs β‡— and code of conduct β‡— to get started.

πŸŽ‰ Thanks

Prism is built on top of lots of excellent packages, and here are a few we'd like to say a special thanks to.

Check these projects out!

🌲 Sponsor Prism by Planting a Tree

If you would like to thank us for creating Prism, we ask that you buy the world a tree.

prism's People

Contributors

billiegoose avatar brendarearden avatar chohmann avatar chris-miaskowski avatar daniel-white avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar edvinyard avatar fcasad avatar heitortsergent avatar ilanashapiro avatar jasonbarry avatar jbl428 avatar karol-maciaszek avatar ksoviero-stoplight avatar lag-of-death avatar mnaumanali94 avatar nulltoken avatar p0lip avatar pamgoodrich avatar pytlesk4 avatar radzserg avatar rainum avatar raysalty avatar ryotrellim avatar stoplight-bot avatar tbarn avatar treyturner avatar xvincentx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prism's Issues

can't use parse-able numbers as scenario IDs

Prism will choke on the below with "Invalid Scenario format json: cannot unmarshal array into Go struct field .scenarios of type map[string]json.RawMessage.". If you change the scenario id from "100" to "foo", it will work.

{
  "scenarioVersion": "1.1",
  "name": "test collection",
  "before": {},
  "scenarios": {
    "100": {
      "name": "test",
      "steps": [
        {
          "id": "ryxe",
          "type": "http",
          "name": "",
          "input": {
            "method": "get",
            "url": "https://api.github.com/gists"
          }
        }
      ]
    }
  },
  "after": {},
  "utilities": {}
}

Finalize initial JS runtime API

Lockdown initial runtime API

JS runtime libraries

  • lodash
  • json schema faker
    • fix date format

Contract testing 204 no content oddities.

Version: 2.0.0-alpha.3
Context: Conductor

Needs verification.

Scenario step sends HTTP request, with response status 204 (no content) after a DELETE operation.

The body shown in the UI is β€œundefined” whereas my API writes nothing at all on output. Therefore, the contract testing always fails.

Found a workaround in declaring an output model as β€œstring” and β€œoptional” but it’s not true.

Integer query param with "[" in it throws "invalid type" error

I'm currently using prism to mock an api endpoint where one of the query parameters is called page[limit], with a type of integer. The mock api works fine if I omit this query param, but when I make a request with the query string ?page%5Blimit%5D=100, it throws this error:

{
  "errors": [
    {
      "context": "request.url.queryString",
      "description": "Invalid type. Expected: [array,integer], given: string",
      "field": "page[limit]",
      "location": "page[limit]",
      "type": "invalid_type"
    }
  ]
}

This error isn't thrown if I change the name of the param to limit, or if I change the type to string.

Am I doing something wrong here, or is this a bug?

Graceful handling of invalid request body JSON

Right now, if a scenario has 3 steps, and step 2 has a request body with invalid JSON, we fail out THE ENTIRE scenario without any sort of useful error, and no data returned for the UI.

Instead, we should probably:

  1. add a log entry to the step with an error description ("Request body JSON is invalid", or something similar)
  2. do not continue running the scenario
  3. when the run is complete, return the result

Request for a docker version

Other than installing in mac or windows, I want to have the same experiencing under linux platform. And docker is the best option.

Excessive memory usage on Ubuntu16

Hi, I am using prism on Amazon Ec2 instance with following OS :
Distributor ID: Ubuntu Description: Ubuntu 16.04.1 LTS Release: 16.04 Codename: xenial

After few requests, as i checked its memory usage went upto 2GB's.

support 302 response code

302 response codes are often used to indicate browser redirection as part of oauth flows. Prism should support automatically using the Location response header to create a new request and "follow the redirect", as a browser would.

configurable concurrency

In some situations, it is not desirable to have all scenarios in a collection run concurrently.

Simplest configuration would be sequential versus parallel (what we have now).

setup + teardown scenario support

Add "setup" and "teardown" properties to collections.

{
    "setup": {...scenario}, // run at start collection
    "scenarios": [], // run concurrently, after setup
    "utilities": [], // not run with collection
    "teardown": {...scenario} // run after scenarios are all completed
}
  • add to prism
  • update docs
  • update json schema / model in docs

Build that runs on Alpine Linux?

We have a Rails app with prism as part of its test suite. The alphas run fine on images based on ruby:2.4-slim, but when I tried running one on an image based on alpine:3.6, I got No such file or directory errors. When I run ldd on the binary, I get this:

bash-4.3# ldd /usr/bin/prism
    /lib64/ld-linux-x86-64.so.2 (0x5588243ac000)
    libm.so.6 => /lib64/ld-linux-x86-64.so.2 (0x5588243ac000)
    libpthread.so.0 => /lib64/ld-linux-x86-64.so.2 (0x5588243ac000)
    libc.so.6 => /lib64/ld-linux-x86-64.so.2 (0x5588243ac000)
Error relocating /usr/bin/prism: __isnan: symbol not found
Error relocating /usr/bin/prism: __finite: symbol not found

In this page from the Docker alpine docs, it says that because Alpine uses musl libc instead of glibc, the binary would need to be compiled natively for musl in order to work. Is this something you could do? Or is there any other way we could run it in our alpine containers?

Add JS runtime flow control + extra helpers

Additional runtime methods:

  • $$.done() - stops collection run

  • $.retry() - stops and retries scenario

  • $.done() - stops scenario

  • $.nextStep(stepId) - moves to next step, or specified id

  • $.pushStep() - adds step to end of scenario

  • $.retryStep() - stops and retries the current step

  • SL.json2xml()

  • SL.xml2json()

  • fetch - need sync and async

Open Source Prism

This is a placeholder issue, more details coming soon.

Currently cleaning up everything and adding some tests.

Error "Header is required"

With this YAML

swagger: '2.0'
info:
  version: '0.1'
  title: test
host: localhost:4010
basePath: /
schemes:
  - http
consumes:
  - text/plain
produces:
  - text/plain
paths:
  '/endpoint':
    get:
      parameters:
        - name: MyApp-MyHeader
          type: string
          in: header
          required: true
      responses:
        '200':
          description: ''

imported to and making request with Postman, Prism tells me (Wireshark stream dump):

GET /endpoint HTTP/1.1
cache-control: no-cache
Postman-Token: 90481f7f-64e7-4df4-9094-1851542c828a
MyApp-MyHeader: efuqhwfieuhqweiufhqwuiefh
User-Agent: PostmanRuntime/3.0.11-hotfix.2
Accept: */*
Host: localhost:4010
accept-encoding: gzip, deflate
Connection: keep-alive

HTTP/1.1 400 Bad Request
Content-Type: application/json
Prism-Request-Messages: [{"messageType":"error","text":"{\n  \"context\": \"request.headers\",\n  \"description\": \"MyApp-MyHeader is required\",\n  \"field\": \"MyApp-MyHeader\",\n  \"location\": \"(root)\",\n  \"type\": \"required\"\n}","createdAt":"2017-03-22T17:46:54.563860678Z"}]
Prism-Request-Validation: Failed
Prism-Response-Hijacked: true
Prism-Response-Mocked: true
Date: Wed, 22 Mar 2017 17:46:54 GMT
Content-Length: 206

{
  "errors": [
    {
      "context": "request.headers",
      "description": "MyApp-MyHeader is required",
      "field": "MyApp-MyHeader",
      "location": "(root)",
      "type": "required"
    }
  ]
}

Any idea what is trying to tell me and what to do about it? Prism console does not say anything useful even with debug parameter.

Mar 22 17:46:25.972 INFO: [ROUTER] {2} Rewriting request host to (localhost:4010)
Mar 22 17:46:26.398 INFO: [VM] Endpoint found (58d2b87277840441750ec7ff, /endpoint, GET, /endpoint)
Mar 22 17:46:26.398 INFO: [VM] Endpoint found (58d2b87277840441750ec7ff, /endpoint, GET, /endpoint)

Well maybe except the fact that it "finds" the endpoint twice for a single request.

Interesting side observation: if i don't use --mock parameter, Prism ends up in endless cycle on very first request:

Mar 22 17:48:14.523 INFO: [ROUTER] {2} Rewriting request host to (localhost:4010)
Mar 22 17:48:14.955 INFO: [VM] Endpoint found (58d2b8de77840441bab52cb4, /endpoint, GET, /endpoint)
Mar 22 17:48:14.955 INFO: [VM] Endpoint found (58d2b8de77840441bab52cb4, /endpoint, GET, /endpoint)
Mar 22 17:48:14.959 INFO: [ROUTER] {4} Rewriting request host to (localhost:4010)
Mar 22 17:48:15.333 INFO: [VM] Endpoint found (58d2b8de77840441bab52cb4, /endpoint, GET, /endpoint)
Mar 22 17:48:15.333 INFO: [VM] Endpoint found (58d2b8de77840441bab52cb4, /endpoint, GET, /endpoint)
Mar 22 17:48:15.335 INFO: [ROUTER] {6} Rewriting request host to (localhost:4010)
Mar 22 17:48:15.735 INFO: [VM] Endpoint found (58d2b8de77840441bab52cb4, /endpoint, GET, /endpoint)
Mar 22 17:48:15.736 INFO: [VM] Endpoint found (58d2b8de77840441bab52cb4, /endpoint, GET, /endpoint)
....

Install.sh is installing Latest version of the tool, which is 2.0.0-alpha.3

Just an FYI: The new version looks like it has some cool features, but the documentation on stoplight.io is still referencing the previous version. I was able to work around this by modifying the local version of the install script, but I'm using the previous version. Would be nice to have documentation on the new version as well.

Add Prism as an NPM module

I've been using this snippet to get it working with Node on Windows:

prism.js

var exec = require('child_process').exec;

// Get the swagger json/yaml file passed in as an arg
var swaggerEndPoint = process.argv[2];

if(!swaggerEndPoint){
    console.error("No swagger endpoint given");
    return;
}

var prism = exec('prism_windows_386.exe run --mock --list --spec ' + swaggerEndPoint);  

prism.stdout.on('data', function(data) {
    console.log(data); 
});

and they use it with node like: C:\>node prism http://petstore.swagger.io/v2/swagger.json

Which works fine but I obviously need prism_windows_386.exe checked into source control. It would make this infinitely more usable if prism could just be installed via npm and used like a regular module.

503 Service Unavailable - Remote network

Everything works on localhost just fine, we have deployed Prism on our server and when we access it from local network everything works just fine as well. But when I try to access it (same request) from outside network, the Prism will get (and print into console) the request, but does not send any response. Only later it will send 503 (see attached screenshot). Our network seems to be configured properly, do you have any idea where could be the problem?

--debug flag does not print anything into the console

screen shot 2017-04-13 at 15 09 09

Segmentation fault on CentOS 7

CentOS 7 /usr/local/bin/prism SIGSEGV

Note: It works on macOS Sierra.

$ uname -r
3.10.0-327.el7.x86_64

$ cat /etc/centos-release
CentOS Linux release 7.2.1511 (Core)

Prism segmentation fault - Debug information

# prism
Segmentation fault
$ gdb prism
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-80.el7
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
"/usr/local/bin/prism": not in executable format: File format not recognized
(gdb)
# strace /usr/local/bin/prism
execve("/usr/local/bin/prism", ["/usr/local/bin/prism"], [/* 30 vars */]) = -1 EFAULT (Bad address)
--- SIGSEGV {si_signo=SIGSEGV, si_code=SI_USER, si_pid=16211, si_uid=0} ---
+++ killed by SIGSEGV +++
Segmentation fault (core dumped)
$ file /usr/local/bin/prism
/usr/local/bin/prism: ERROR: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs)error reading (Invalid argument)
$ hexdump -n 16 /usr/local/bin/prism
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000010

Change the amount of data returned by the api

Hello,

Thanks you guys for creating this. It's very helpful for mocking and creating apis.

Do you think it would be possible to add a command line arg, to define how much data is sent by the api ? This would be very helpful when we need some endpoint to return more than just one to 3 lines...

thanks in advance.

Conduct - No error when scenario/collection file doesn't exist or is invalid

When running prism conduct scenario.json where scenario.json doesn't exist yields no output by prism. I would expect some error indicating that the file doesn't exist.

Likewise where scenario.json exists but is not valid, there's no output and I would expect an error indicating a problem with the file.

Add support for $$.ctx

This will persist the ctx during a collection run. This will allow you to persist data in before scenarios.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.