Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

Overview

Prism - API Mock Servers and Contract Testing

CircleCI NPM Downloads Buy us a tree

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

  • 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 3.0, OpenAPI 2.0 (FKA Swagger) and Postman Collections support.

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

Note: This branch refers to 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

Overview

🧰 Installation and Usage

Installation

Prism requires NodeJS >= 12 to properly work.

npm install -g @stoplight/prism-cli

# OR

yarn global add @stoplight/prism-cli

For more installation options, see our installation documentation.

Mocking

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

Validation Proxy

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

📖 Documentation and Community

🚧 Roadmap

  • Content Negotiation
  • Security Validation
  • Validation Proxy
  • Custom Mocking
  • Recording / "Learning" mode to create spec files
  • Data Persistence (allow Prism act like a sandbox)

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.

Is there a hosted version of Prism?

Yes, hosted mocking is available as part of Stoplight Platform. Learn More

⚙️ Integrations

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

🏁 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!

Issues
  • Add support for OpenAPI v3

    Add support for OpenAPI v3

    I was not able to find a similar issue requesting this, so consider it requested :)

    opened by josephgardner 29
  • Detect unresolvable cirular $refs during prism startup

    Detect unresolvable cirular $refs during prism startup

    User story. As an API mock tester, when I startup PRISM and my OpenAPI spec contains an unresolvable $ref, then I want to receive a notification, so that I can try to fix the problem without having to try to fire that request against the mock by myself.

    Is your feature request related to a problem? i have tried to get started with PRISM and I have a spec with DTO models externalized into a separate file. My spec is affected by bug #390. If you experiment with the $refs, you need to try some calls before you know if it works or not. [15:43:16] » [CLI] ► start Prism is listening on http://127.0.0.1:4010 (...) I'm firing a call manually with Postman (...) [15:43:38] » [NEGOTIATOR] √ success Found a compatible content for */* (node:10040) UnhandledPromiseRejectionWarning: Error: Your schema contains $ref. You must provide specification in the third parameter.

    Describe the solution you'd like During startup, Prism tries to resolve the $refs and outputs a warning if calls use unresolvable $refs.

    Additional context Go with a "Fail fast" approach

    t/bug team/platinum-falcons 
    opened by patrickp-at-work 29
  • Change the amount of data returned by the api

    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.

    opened by enyosolutions 28
  • Circular $ref pointer not supported

    Circular $ref pointer not supported

    Describe the bug

    A clear and concise description of what the bug is. Pointing prism to a file that contains components that use recursive field definition, Prism fails with the message:

    Circular $ref pointer found at /tmp/test.yaml#/components/schemas/Person/properties/spouse

    To Reproduce

    A minimal API definition triggering the error message:

    info:
      title: "Circular reference example"
      description: "Exemplifies a schema with circular references"
      version: 0.1.0
    
    paths:
      /directory:
        get:
          responses:
            "200":
              description: "The request was successfully processed"
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/Person"
                  example:
                    name: John
                    spouse:
                      name: Cynthia
    
    components:
    
      schemas:
    
        Person:
          nullable: true
          properties:
            name:
              type: string
              nullable: false
            spouse:
              $ref: "#/components/schemas/Person"
    

    Expected behavior

    As the OAS file specifies a valid API, the server should be able to mock that API. While having a circular reference can theoretically lead to a infinite recursion, this can be in practice avoided by having a nullable reference to the child object.

    Environment

    • Prism version: [4.1.0]
    t/bug team/platinum-falcons p/high 
    opened by marcoboi 27
  • [BUG] Prism should support */* by default for DELETE

    [BUG] Prism should support */* by default for DELETE

    I have a simple DELETE endpoint and want to return empty with a 204

    Documentation says

    "Some responses, such as 204 No Content, have no body. To indicate the response body is empty, do not specify a content for the response"

    https://swagger.io/docs/specification/describing-responses/

     /api/calls/{id}:
        delete: # DELETE
          tags:
            - Calls
          description: Delete a call history item
          parameters:
            - $ref: '#/components/parameters/id'
          responses:
            204:
              description: OK
            400:
              description: NOK
            500:
              description: ERROR
    components:
        id:
          in: path
          name: id
          description: id for the item
          required: true
          schema:
            type: integer
            format: int64
    
    
    curl -X DELETE "http://127.0.0.1:4010/api/calls/1" -H "accept: */*"
    or
    curl -X DELETE "http://127.0.0.1:4010/api/calls/1"  
    
    {
    detail: "Unable to find content for application/json, text/plain, */*"
    status: 406
    title: "The server cannot produce a representation for your accept header"
    type: "https://stoplight.io/prism/errors#NOT_ACCEPTABLE"        
    }   
    

    The following is a workaround but it seems like it is pollution in my spec file

      /api/calls/{id}:
        delete: # DELETE
          tags:
            - Calls
          description: Delete a call history item
          parameters:
            - $ref: '#/components/parameters/id'
          responses:
            204:
              description: OK
              content:
                '*/*':
                  schema:
                    type: string
            400:
              description: NOK
            500:
              description: ERROR
    
    t/bug 
    opened by lfmunoz 25
  • Postman plus Prism Proxy causes errors

    Postman plus Prism Proxy causes errors

    Describe the bug I use Postman (https://www.postman.com/) with Prism, with good results. When I put Prism into proxy mode, Postman thinks it didn't get a response (but curl to the same endpoint works fine).

    Prism shows no error messages, the output from Prism is identical whether I make the request through Postman or curl

    Postman's console says "incorrect header check"

    curl shows that Prism is returning a header content-encoding: gzip, which I don't get when I request the live API directly rather than via the Prism proxy.

    To Reproduce

    1. Given this OpenAPI document (actually I'm not sure it matters but I'm using https://github.com/Nexmo/api-specification/blob/master/definitions/verify.yml and hitting the search/ endpoint
    2. Run this CLI command prism proxy verify.yml https://api.nexmo.com/verify
    3. Make a request to the Search endpoint using Postman

    Expected behavior The API response

    Environment (remove any that are not applicable):

    • Library version: 3.2.9
    • OS: Ubuntu 18.04
    • Postman 7.21.1
    • curl: 7.58.0

    Additional context I managed to get things working by adding an additional header to Postman Accept-Encoding and leaving it empty - I think Postman sends this header by default. However curl does not send Accept-Encoding by default and I still see that Prism returns a content-encoding: gzip to curl so while I'm not sure Postman is sending correct headers, I think Prism is also adding something here that doesn't help!

    bug team/platinum-falcons 
    opened by lornajane 24
  • Proxy behaves like mock when upstream returns 501, proxy otherwise

    Proxy behaves like mock when upstream returns 501, proxy otherwise

    User story.

    As a dev, I can do run proxy getting real values from upstream when a route has been implemented upstream, and mocked values when a route has not been implemented upstream, so that I can get the best of both worlds.

    Is your feature request related to a problem?

    I'd like to get real data as soon as it's available, but also continue to get mocked data for routes that are not yet implemented.

    Describe the solution you'd like

    When upstream returns 501 (not implemented), prism behaves as it does in mock mode. Else, it behaves as in proxy mode.

    Additional context

    Add any other context or screenshots about the feature request here.

    t/enhancement t/feature p/medium team/platinum-falcons 
    opened by sandinmyjoints 21
  • [Bug] 422 Response Not Being Used For Validation Response

    [Bug] 422 Response Not Being Used For Validation Response

    Describe the bug

    Hello! I could really use some help and guidance!

    I have an Open API spec that is valid when I used Spectral

    I can successfully run it with Prism

    I have unit tests that validate an endpoint, so I am using Prism like so prism proxy --errors example.yaml http://localhost:8080

    When I send an invalid request it keeps giving me this error

    {
      type: 'https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY',
      title: 'Invalid request',
      status: 422,
      detail: 'Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.',
      validation: [
        {
          location: [Array],
          severity: 'Error',
          code: 'required',
          message: "should have required property 'firstname'"
        },
        {
          location: [Array],
          severity: 'Error',
          code: 'required',
          message: "should have required property 'lastname'"
        },
        {
          location: [Array],
          severity: 'Error',
          code: 'required',
          message: "should have required property 'email'"
        },
        {
          location: [Array],
          severity: 'Error',
          code: 'required',
          message: "should have required property 'password'"
        }
      ]
    }
    

    Which is wild because this DOES exist.

    It keeps stating Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you which is not true at all because I have a 422 response declared for the endpoint that's being hit!

    I have tried setting a 400 response. I've tried setting different data for the response. And nothing is working.

    What am I doing wrong?

    To Reproduce

    Use this file

    ---
    openapi: '3.0.2'
    
    servers:
        - url: http://localhost:8080
          description: Local deployment from your computer
    
    paths:
        /api/users/register:
            post:
                summary: 'Register New User'
                description: 'Register a new user'
                operationId: 'registerNewUser'
                tags: ['Users']
                requestBody:
                    required: true
                    content:
                        application/json:
                            schema:
                                type: 'object'
                                properties:
                                    firstname:
                                        type: 'string'
                                        minLength: 2
                                        maxLength: 100
                                        example: 'John'
                                    lastname:
                                        type: 'string'
                                        minLength: 2
                                        maxLength: 100
                                        example: 'Roberts'
                                    email:
                                        type: 'string'
                                        minLength: 4
                                        maxLength: 100
                                        example: '[email protected]'
                                    password:
                                        type: 'string'
                                        minLength: 8
                                        maxLength: 50
                                        example: 'abc123456'
                                required:
                                    - firstname
                                    - lastname
                                    - email
                                    - password
                responses:
                    '201':
                        description: Successful registration of a new user
                    '422':
                        description: Failed to register new user
                        content:
                            application/json:
                                schema:
                                    type: 'object'
                                    properties:
                                        message:
                                            type: 'string'
                                            example: 'firstname is required'
    

    Run prism proxy --errors example.yaml http://localhost:8080

    Run this curl command to confirm it works

    curl --location --request POST 'localhost:4010/api/users/register' \
    --header 'Content-Type: application/json' \
    --data-raw '{
    	"firstname": "First",
    	"lastname": "Last",
    	"email": "[email protected]",
    	"password": "This_is_4_str0ng_password!"
    }'
    

    If you want pretty printing you can add json_pp

    curl --location --request POST 'localhost:4010/api/users/register' \
    --header 'Content-Type: application/json' \
    --data-raw '{
    	"firstname": "First",
    	"lastname": "Last",
    	"email": "[email protected]",
    	"password": "This_is_4_str0ng_password!"
    }'
    

    Run this command to confirm it fails

    curl --location --request POST 'localhost:4010/api/users/register' \
    --header 'Content-Type: application/json' \
    --data-raw '{}'
    

    Same, but with pretty printing

    curl --location --request POST 'localhost:4010/api/users/register' \
    --header 'Content-Type: application/json' \
    --data-raw '{}' | json_pp
    

    And the final output is this

    ~/Repositories/example   feature/api_spec_and_test_reconciliation ±  ⬡ v12.17.0  curl --location --request POST 'localhost:4010/api/users/register' \
    --header 'Content-Type: application/json' \
    --data-raw '{}' | json_pp
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100   702  100   700  100     2   113k    333 --:--:-- --:--:-- --:--:--  114k
    {
       "detail" : "Your request is not valid and no HTTP validation response was found in the spec, so Prism is generating this error for you.",
       "title" : "Invalid request",
       "type" : "https://stoplight.io/prism/errors#UNPROCESSABLE_ENTITY",
       "status" : 422,
       "validation" : [
          {
             "severity" : "Error",
             "location" : [
                "body"
             ],
             "message" : "should have required property 'firstname'",
             "code" : "required"
          },
          {
             "message" : "should have required property 'lastname'",
             "location" : [
                "body"
             ],
             "severity" : "Error",
             "code" : "required"
          },
          {
             "code" : "required",
             "severity" : "Error",
             "location" : [
                "body"
             ],
             "message" : "should have required property 'email'"
          },
          {
             "message" : "should have required property 'password'",
             "location" : [
                "body"
             ],
             "severity" : "Error",
             "code" : "required"
          }
       ]
    }
    

    Expected behavior

    I expect the responses I created for 422 to be used so that I don't have to worry about Prism returning different payloads than what my server does.

    Questions

    How do I get Prism to not return a generated 422 override?

    Because it keeps generating that validation response I can't integrate it with my tests, because the tests expect a message property to be there.

    I've read through the documentation here:

    • https://meta.stoplight.io/docs/prism/docs/guides/errors.md#unprocessable_entity
    • https://meta.stoplight.io/docs/prism/docs/guides/02-request-validation.md#request-validation

    And none of it provides an explicit example on how to make it so that Prism does not return an auto-generated response.

    Additional context

    • Prism: 4.1.2
    • OS: MacOS
    bug 
    opened by loganknecht 20
  • feat(JSONSchema): Programmatically extend JSON Schema Faker

    feat(JSONSchema): Programmatically extend JSON Schema Faker

    Checklist

    • [x] Tests have been added (for bug fixes / features)
    • [ ] Docs have been added / updated (for bug fixes / features)

    What kind of change does this PR introduce?

    Feature

    Programatically extend JSON Schema Faker options, formats and keywords.

    The provided solution implemented in #384 is not sufficient for certain use-cases.

    Eg. Generated HTML, localized Faker support, custom functions, etc.

    The goal is to be as randomly realistic to the production API as possible.

    What is the current behavior? What is the new behavior?

    The new behaviour allows custom JSON Schema Faker options, formats and keywords to be added when using the Prism mocking server programmatically.

    The OpenAPI spec allow custom formats for the properties with the type string and custom keywords using extensions

    Example: mocking-server.js

    const { createServer } = require("@stoplight/prism-http-server");
    const { createLogger } = require("@stoplight/prism-core");
    const minimist = require("minimist");
    const { loremIpsum } = require("lorem-ipsum");
    const Chance = require('chance');
    
    
    const { port = 3001, schema: path } = minimist(process.argv);
    
    const JSONSchemaFakerConfig = {
      options: {
        // Available options: https://github.com/json-schema-faker/json-schema-faker/tree/master/docs#available-options
        maxItems: 100,
      },
    
      // https://github.com/json-schema-faker/json-schema-faker/blob/master/docs/USAGE.md#custom-formats
      customFormats: {
        html: loremIpsum({
          count: 5,
          format: "plain",
          units: "paragraphs"
        });
      },
    
      // https://github.com/json-schema-faker/json-schema-faker/blob/master/docs/USAGE.md#extending-dependencies
      extensions: {
        chance: () => {
          const chance = new Chance();
    
          chance.mixin({
            user: () => {
              const first = chance.first();
              const last = chance.last();
              const email = chance.email();
              return `${first} ${last} – ${email}`;
            }
          });
    
          return chance;
        }
      }
    }
    
    const server = createServer(
      { path },
      {
        config: { mock: { dynamic: JSONSchemaFakerConfig } },
        components: {
          logger: createLogger()
        }
      }
    );
    
    server.listen(port).then(() => {
      console.log(`🤖 Mocking server enabled on port ${port}`);
    });
    

    Does this PR introduce a breaking change?

    No.

    opened by vanhoofmaarten 19
  • CORS Headers Options verb

    CORS Headers Options verb

    User story. As a frontend developer, I want to connect to the local mock server, so that I can see mocked responses in my browser.

    Is your feature request related to a problem? I can not connect to the mock server via a secure browser, as the CORS Headers are not set up correctly to allow any origin and any verb (OPTIONS, GET, POST, PATCH, etc.)

    Describe the solution you'd like The stoplight client mock server is sending out widely set CORS headers to allow any origin and any verb - or it allows me to configure it myself.

    Additional context Screenshot 2020-03-03 at 09 55 02

    opened by Primajin 19
  • for input validation, readOnly properties inside allOf are omitted from normalized schema

    for input validation, readOnly properties inside allOf are omitted from normalized schema

    Addresses #1920

    Summary

    When validating input, readOnly properties inside allOf should be omitted from normalized schema. That is, it should never be required to supply a readOnly property in input. Prior to this change, if the readOnly attribute was used within an allOf, it was not correctly removed from the "normalized" schema against which we'll validate.

    Checklist

    • The basics
      • [x] I tested these changes manually in my local or dev environment
    • Tests
      • [x] Added or updated
      • [ ] N/A
    • Event Tracking
      • [ ] I added event tracking and followed the event tracking guidelines
      • [x] N/A
    • Error Reporting
      • [ ] I reported errors and followed the error reporting guidelines
      • [x] N/A

    Additional context

    Some open questions exist; see comments inline in changes/diffs.

    opened by EdVinyard 1
  • honor x-schema-faker settings when mocking from Ninja

    honor x-schema-faker settings when mocking from Ninja

    follow-up to investigate Pass x- settings to Prism when mocking from Ninja

    Goal

    When a workspace-project-branch OAS specification includes x-schema-faker options, the mock responses to ninja by the mocks component should honor those options.

    Two possible implementation strategies, both with significant drawbacks:

    1. Pass a pre-configured JSF instance into Prism's mock() function. In mocks, cache pre-configured JSF instances based on workspace-project-branch, and figure out how to invalidate this cache when each specification changes. Drawback: This exposes Prism implementation details (that JSF is used) to its client, mocks.

    2. Introduce the concepts of workspace, project, and branch into Prism (or at the very least the notion of distinct Prism configurations). This also requires that the configuration (or a placeholder/key) be supplied along with requests. Drawback: Prism should not know anything about multiple configurations, especially regarding workspaces, projects, and branches.

    Note: This probably requires changes to both mocks and prism regardless of the implementation strategy.

    Background

    mocks uses prism to generate mock reponses. prism in turn uses json-schema-faker (JSF). Specifically, prism:

    • uses a single, global instance of JSF,
    • lacks any contextual knowledge (workspace, project, or branch), and
    • isn't passed any "top level" specification information that could be used to configure the JSF instance appropriately

    The current code-path is traced in detail below.

    in mocks, handleRequest()

    in platform-internal/packages/mocks/src/index.ts, handleRequest() calls validateInputAndMock()

        function handleRequest(
          req: IncomingMessage,
          { workspaceSlug, projectSlug, serviceNodeId, 
            prismUrl, branchName: branch }: ApiLocationInfo,
          config: IHttpOperationConfig,
        ) {
          ...
    
          TE.bindW('response', ({ input, resolved }) => TE.fromEither(validateInputAndMock(resolved, input, config)(logger))),
          ...
    

    in mocks, validateInputAndMock()

    in platform-internal/packages/mocks/src/index.ts, validateInputAndMock() calls mock()

        import mock from '@stoplight/prism-http/dist/mocker';
    
        function validateInputAndMock(
          resource: IHttpOperation, 
          element: IHttpRequest, 
          config: IHttpOperationConfig
        ) {
          logger.error('validateInputAndMock()');
          return pipe(
            validateInput({ resource, element }),
            E.fold<IPrismDiagnostic[], unknown, IPrismDiagnostic[]>(
              validations => validations,
              () => [],
            ),
            validations => mock({ 
              resource, 
              input: { data: element, validations }, 
              config 
            }),
          );
        }
    

    in prism, mock()

    Notice that Prism lacks any concept of workspaces, projects, or branches. Furthermore, Prism lacks any way to retrieve that information.

    in prism/packages/http/src/mocker/index.ts, mock() calls generate()

        import { generate, generateStatic } from './generator/JSONSchema';
    
        const mock = (...) => {
          const payloadGenerator: PayloadGenerator = config.dynamic
            ? partial(generate, resource['__bundled__'])
            : partial(generateStatic, resource);      
        }
    

    Prism uses a single, global instance of json-schema-faker (JSF). This works well when it's started from the command line, but when run from mocks, we need a JSF instance configured per workspace-project-branch.

    in prism, generate()

    in prism/packages/http/src/mocker/generator/JSONSchema.ts, generate() calls json-schema-faker's generate()

        import * as jsf from 'json-schema-faker';
    
        jsf.extend('faker', () => faker);
        jsf.option({
          failOnInvalidTypes: false,
          failOnInvalidFormat: false,
          alwaysFakeOptionals: true,
          optionalsProbability: 1 as any,
          fixedProbabilities: true,
          ignoreMissingRefs: true,
          maxItems: 20,
          maxLength: 100,
        });
    
        generateKeyPair(...) {
          jsf.generate( ... )
        }
    
    opened by EdVinyard 1
  • Validation proxy with company proxy

    Validation proxy with company proxy

    Describe the bug

    Prism does not allow positioning a company proxy between it and the backend in proxy mode.

    Environment (remove any that are not applicable):

    • Library version: 4.4.1
    • OS: Ubuntu 20.04
    opened by ClementDEBOOS 0
  • Dynamic generation of pattern with invalid value should be overwritten by example value

    Dynamic generation of pattern with invalid value should be overwritten by example value

    Describe the bug

    For some regex patterns, the json-schema-faker fails to generate a valid value that matches the pattern.

    To Reproduce

    This pattern rarely produces a valid response

        Language:
          type: object
          properties:
            languageId:
              description: ISO language code (http://www.mathguide.de/info/tools/languagecode.html)
              example: en-Latn-US
              type: string
              pattern: ^[aA-zZ]{2}(-[aA-zZ]{4})?(-[aA-zZ]{2})?$
    

    Expected behavior

    The invalid value should not be returned if there is an example in the object property.

    Indeed, the invalid value will potentially create test failures that make tests flaky. I would like that the value returned by the example if provided in the case that the generated pattern doesn't match.

    In the example provided above, the generator would try to create a valid value matching the pattern ^[aA-zZ]{2}(-[aA-zZ]{4})?(-[aA-zZ]{2})?$. In case of failure, the generated value would be overwritten by en-Latn-US

    opened by gbmarc1 0
  • Nested schema in oneOf ignores validation rule of readOnly property

    Nested schema in oneOf ignores validation rule of readOnly property

    Describe the bug

    When validating request body that contains a oneOf that has a schema with a required readOnly property, prism returns a 422 response stating that the readOnly properties must be include in the request body.

    To Reproduce

    1. Given this OpenAPI document
    openapi: 3.0.3
    
    info:
      title: OneOf
      version: 0.0.0
    
    paths:
    
      /resources:
    
        post:
          summary: Register a resource
          operationId: apis.v1.resources.post
          requestBody:
            description: The release to be registered
            required: true
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/Source'
          responses:
            201:
              description: Confirmation of resource registration
              content:
                application/json:
                  schema:
                    $ref: '#/components/schemas/Resource'
    
    components:
      schemas:
      
        ResourceRef:
          type: object
          properties:
            resourceId:
              description: Resource identifier reference (/resources/{resourceId})
              type: integer
              minimum: 1
              example: 1
          additionalProperties: false
          required:
            - resourceId
        Resource:
          type: object
          properties:
            resourceId:
              description: ID of the resource
              type: integer
              readOnly: true
              minimum: 1
            name:
              description: User-defined name of the resource
              type: string
    
        Source:
          oneOf:
            - $ref: '#/components/schemas/ResourceRef'
            - $ref: '#/components/schemas/Resource'
    
    1. Run this CLI command 'prism mock -d openApi.yaml.'
    2. Post to '/resources' with request body
    {
        "name": "Test Resource"
    }
    

    Expected behavior

    Prism should recognize that the request body is valid and return 201

    If request body content schema is replaced with Resource it works as expected as per #1142

    opened by LucCelny 0
  • Return request body as response

    Return request body as response

    Hello, Is there a way to return the same request body as a response (echo API) ? I want to retreive the body object and return it in the body response. Thank you for your help

    opened by hsnsalhi 0
  • Prism 4.6 Returning

    Prism 4.6 Returning "Bad Request" when Content-Type header is set

    Describe the bug

    After upgrading Prism from 4.5 to 4.6, requests that specify a content-type header return with the following error message: [6:24:06 AM] › [VALIDATOR] ✖ error Violation: request Supported content types:

    To Reproduce

    1. Given this OpenAPI document (see attached) swagger.txt

    2. Run Prism

    3. Make a request with Content-Type: application/json

    4. The request will return a 400

    Expected behavior

    The request should return a 200

    Additional context

    We're running this on Docker with the public images. Rolling back to 4.5 works as expected (and thank you for such a nice product!)

    Screenshots

    Environment (remove any that are not applicable):

    • Library version: 4.6
    • OS: Mac OS (although Prism is running in the Docker images provided by Stoplight
    • Browser: Curl
    • Platform:
    opened by xero-timothy 0
  • Add custom implementation of operation

    Add custom implementation of operation

    Summary

    Want to add some VERY primitive dynamic behaviour of API (show download progress).

    Are there any ways to get into prism response generation mechanism and put there some hooks?

    opened by maxlapshin 0
  • Use accurate content-type matching

    Use accurate content-type matching

    User story.

    As I user I expect prism to pick proper contents element based on more accurate content-type matching.

    Is your feature request related to a problem?

    Follow up on #1813

    Describe the solution you'd like

    Assuming I have an operation with following content-type in request bodies:

    • application/json
    • application/vnd+json
    • application/vnd.1+json

    And sending request with content-type: application/vnd.1+json then the request body for content-type application/vnd.1+json will be picked since that's the most accurate match.

    t/enhancement 
    opened by lukasz-kuzynski-11sigma 0
  • Prism fails to send a response if validation pattern contains non-ascii characters

    Prism fails to send a response if validation pattern contains non-ascii characters

    Describe the bug

    Prism fails to send a response if specification's validation pattern contains non-ascii characters. Request is stuck forever.

    To Reproduce

    1. Given this OpenAPI document spec.yaml
    swagger: '2.0'
    info:
      title: bug
      version: 1.0.2
    schemes:
      - https
    basePath: /
    produces:
      - application/json
    consumes:
      - application/json
    definitions:
      GenericError:
        type: object
        required:
          - httpCode
        properties:
          httpCode:
            type: string
            example: '400'
            maxLength: 3
        additionalProperties: false
      Info:
        additionalProperties: false
        properties:
          city:
            type: string
            pattern: '^[А-ЯЁа-яё]+([- ][А-ЯЁа-яё]+)*$'
        type: object
    paths:
      /:
        post:
          consumes:
            - application/json
          produces:
            - application/json
          parameters:
            - in: body
              name: body
              description: body
              required: true
              schema:
                $ref: '#/definitions/Info'
          responses:
            '422':
              schema:
                $ref: '#/definitions/GenericError'
          operationId: create
    
    1. Run this CLI command prism mock spec.yaml
    2. Send POST to localhost:4010
    curl --request POST \
      --url http://localhost:4010/ \
      --header 'accept: application/json' \
      --header 'content-type: application/json' \
      --data '{
    	"city": "fdgfg"
    }'
    
    1. Request is stuck forever
    2. See error message in logs
    [10:29:45 AM] › [HTTP SERVER] post /applications ℹ  info      Request received
    [10:29:45 AM] ›     [NEGOTIATOR] ℹ  info      Request contains an accept header: application/json
    [10:29:45 AM] ›     [VALIDATOR] ⚠  warning   Request did not pass the validation rules
    [10:29:45 AM] ›     [NEGOTIATOR] ✔  success   Found response 422. I'll try with it.
    [10:29:45 AM] ›     [NEGOTIATOR] ⬤  debug     Unable to find a content with an example defined for the response 422
    [10:29:45 AM] ›     [NEGOTIATOR] ✔  success   The response 422 has a schema. I'll keep going with this one
    [10:29:45 AM] ›     [NEGOTIATOR] ✔  success   Responding with the requested status code 422
    (node:22298) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["sl-violations"]
        at ServerResponse.setHeader (_http_outgoing.js:561:3)
        at /usr/local/lib/node_modules/@stoplight/prism-cli/node_modules/@stoplight/prism-http-server/dist/server.js:69:23
        at /usr/local/lib/node_modules/@stoplight/prism-cli/node_modules/fp-ts/lib/function.js:184:30
        at /usr/local/lib/node_modules/@stoplight/prism-cli/node_modules/fp-ts/lib/EitherT.js:52:116
        at /usr/local/lib/node_modules/@stoplight/prism-cli/node_modules/fp-ts/lib/Task.js:142:37
        at processTicksAndRejections (internal/process/task_queues.js:93:5)
    (node:22298) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 6)
    

    Expected behavior

    An error message response was sent to the client.

    Environment (remove any that are not applicable):

    • Library version: 4.5.0
    • OS: Macos
    • Browser: Insomnia
    • Platform: CLI
    opened by RomanKornev 0
Releases(v4.6.1)
Owner
Stoplight
Stoplight leverages your OpenAPI documents to drive the entire API development process
Stoplight
A mocking library for requests

httmock A mocking library for requests for Python 2.7 and 3.4+. Installation pip install httmock Or, if you are a Gentoo user: emerge dev-python/httm

Patryk Zawadzki 432 Nov 23, 2021
HTTP client mocking tool for Python - inspired by Fakeweb for Ruby

HTTPretty 1.0.5 HTTP Client mocking tool for Python created by Gabriel Falcão . It provides a full fake TCP socket module. Inspired by FakeWeb Github

Gabriel Falcão 1.9k Nov 29, 2021
A utility for mocking out the Python Requests library.

Responses A utility library for mocking out the requests Python library. Note Responses requires Python 2.7 or newer, and requests >= 2.0 Installing p

Sentry 3.4k Nov 27, 2021
A utility for mocking out the Python Requests library.

Responses A utility library for mocking out the requests Python library. Note Responses requires Python 2.7 or newer, and requests >= 2.0 Installing p

Sentry 3.1k Feb 8, 2021
HTTP client mocking tool for Python - inspired by Fakeweb for Ruby

HTTPretty 1.0.5 HTTP Client mocking tool for Python created by Gabriel Falcão . It provides a full fake TCP socket module. Inspired by FakeWeb Github

Gabriel Falcão 1.9k Feb 6, 2021
A mocking library for requests

httmock A mocking library for requests for Python 2.7 and 3.4+. Installation pip install httmock Or, if you are a Gentoo user: emerge dev-python/httm

Patryk Zawadzki 419 Feb 2, 2021
Asyncio http mocking. Similar to the responses library used for 'requests'

aresponses an asyncio testing server for mocking external services Features Fast mocks using actual network connections allows mocking some types of n

null 84 Nov 24, 2021
Wraps any WSGI application and makes it easy to send test requests to that application, without starting up an HTTP server.

WebTest This wraps any WSGI application and makes it easy to send test requests to that application, without starting up an HTTP server. This provides

Pylons Project 306 Nov 19, 2021
Parameterized testing with any Python test framework

Parameterized testing with any Python test framework Parameterized testing in Python sucks. parameterized fixes that. For everything. Parameterized te

David Wolever 623 Dec 2, 2021
A collection of testing examples using pytest and many other libreris

Effective testing with Python This project was created for PyConEs 2021 Check out the test samples at tests Check out the slides at slides (markdown o

Héctor Canto 5 Oct 21, 2021
A modern API testing tool for web applications built with Open API and GraphQL specifications.

Schemathesis Schemathesis is a modern API testing tool for web applications built with Open API and GraphQL specifications. It reads the application s

Schemathesis.io 1.1k Nov 25, 2021
A modern API testing tool for web applications built with Open API and GraphQL specifications.

Schemathesis Schemathesis is a modern API testing tool for web applications built with Open API and GraphQL specifications. It reads the application s

Schemathesis.io 1.1k Nov 29, 2021
MultiPy lets you conveniently keep track of your python scripts for personal use or showcase by loading and grouping them into categories. It allows you to either run each script individually or together with just one click.

MultiPy About MultiPy is a graphical user interface built using Dear PyGui Python GUI Framework that lets you conveniently keep track of your python s

null 49 Oct 31, 2021
Cornell record & replay mock server

Cornell: record & replay mock server Cornell makes it dead simple, via its record and replay features to perform end-to-end testing in a fast and isol

HiredScoreLabs 121 Nov 25, 2021
Django-google-optimize is a Django application designed to make running server side Google Optimize A/B tests easy.

Django-google-optimize Django-google-optimize is a Django application designed to make running Google Optimize A/B tests easy. Here is a tutorial on t

Adin Hodovic 31 Nov 24, 2021
Automating the process of sorting files in my downloads folder by file type.

downloads-folder-automation Automating the process of sorting files in a user's downloads folder on Windows by file type. This script iterates through

Eric Mahasi 20 Nov 25, 2021
ApiPy was created for api testing with Python pytest framework which has also requests, assertpy and pytest-html-reporter libraries.

ApiPy was created for api testing with Python pytest framework which has also requests, assertpy and pytest-html-reporter libraries. With this f

Mustafa 1 Jul 15, 2021
AutoExploitSwagger is an automated API security testing exploit tool that can be combined with xray, BurpSuite and other scanners.

AutoExploitSwagger is an automated API security testing exploit tool that can be combined with xray, BurpSuite and other scanners.

null 6 Nov 19, 2021
API Test Automation with Requests and Pytest

api-testing-requests-pytest Install Make sure you have Python 3 installed on your machine. Then: 1.Install pipenv sudo apt-get install pipenv 2.Go to

Sulaiman Haque 2 Nov 21, 2021