Prism

repository·master·Indexed 26 days ago

https://github.com/stoplightio/prism

A toolset for API mocking and contract testing supporting OpenAPI v2, v3.0, v3.1, and Postman Collections. Prism provides a CLI for spinning up mock servers and validation proxies, as well as programmatic libraries including @stoplight/prism-http for OpenAPI-based mocking and request validation, and @stoplight/prism-http-server for creating mock/validation servers.

Tokens
18.4K
Snippets
49
Records
120
Agent score
89%

What's inside Prism

  1. Understand Prism Mocking

    master

    Prism provides a mock HTTP server that acts as a fake implementation of an API at the HTTP level. It uses an OpenAPI (v2 or v3) description document as the source of truth to make decisions about responses.

    Key behaviors include:

    • Responding to expected endpoints based on the OpenAPI definition.
    • Erroring for non-existent endpoints.
    • Providing realistic validation errors if a client sends an invalid request.

    Note: Prism is currently an HTTP server run from the command line and is not yet intended for programmatic mocking within test suites.

  2. Understand the Validation Proxy

    master

    A Validation Proxy allows you to sit Prism between a client and a real upstream server to ensure both requests and responses adhere to an OpenAPI specification.

    How it works:

    1. Request Validation: If a client sends an invalid request, Prism will report the error using the same logic as the mock server.
    2. Proxying: If the request is valid, Prism forwards it to the upstream server.
    3. Response Validation: If the upstream server returns a response that is invalid against the provided API description, Prism can error or log the discrepancy.

    You can run this via the CLI by providing the OpenAPI file and the upstream server URL.

    prism proxy openapi.yml http://api.example.com/
  3. Support TLS with Prism using nginx as a TLS termination layer

    master

    Since Prism does not natively support TLS, you can use nginx as a TLS termination proxy. This setup involves using docker compose to run both a Prism service and an nginx service. The nginx service handles the SSL handshake and then proxies the decrypted traffic to Prism over HTTP.

    Required Directory Structure

    To use the following configuration, organize your project as follows:

    📦project-root
     ┣ 📂 nginx
     ┃ ┗ 📜 default.conf
     ┃ 📂 tls
     ┃ ┗ 📜 dhparam.pem
     ┃ ┗ 📜 tls-proxy.crt
     ┃ ┗ 📜 tls-proxy.key
     ┣ 📜 api.oas3.yml
     ┗ 📜 docker-compose.yml
  4. Mock Callbacks with Prism

    master

    Prism can mock OpenAPI 3.x callbacks, which are asynchronous, outgoing requests defined in your specification. When a client makes a request to an endpoint that triggers a callback, Prism will automatically invoke the callback URL specified in the request (or via runtime expressions) with a mocked payload.

    Limitations

    • Prism does not support servers or security definitions inside callback operations.
    • Prism does not support $url or $request.path.* runtime expressions within callbacks.
  5. Install Prism standalone binaries

    master

    If you do not have Node.js or npm installed, you can use standalone binaries. You can install the appropriate package for your operating system using the following shell script. Note that binaries do not automatically update; you must run the script again to install new versions.

    curl -L https://raw.githack.com/stoplightio/prism/master/install | sh
  6. Run a multi-document Prism cluster with Docker Compose

    master

    To run the multi-document setup, ensure your docker-compose.yaml and Caddyfile are in the same directory. Execute the following command from that directory to start the cluster:

    docker-compose up

    Once running, you can verify the endpoints using curl. For example, if using the configuration provided in the guide, you can test the endpoints at:

    • http://localhost:8080/app_1/pets
    • http://localhost:8080/app_2/pets
    docker-compose up
    
    # Testing endpoints
    curl http://localhost:8080/app_1/pets
    curl http://localhost:8080/app_2/pets
  7. Validate server URLs using the __server query parameter

    master

    If your OpenAPI specification defines specific servers, you can use Prism to ensure your requests are being made to a valid, recognized server URL.

    To enforce server validation, append the __server query parameter to your request URL containing the target server's base URL. If the provided URL does not match any of the servers defined in the specification, Prism will return a 404 error with a NO_SERVER_MATCHED_ERROR type.

  8. Configure docker-compose.yml for Prism and nginx TLS proxy

    master

    Use this docker-compose.yml configuration to orchestrate Prism and an nginx TLS proxy. The prism service exposes port 4010 to the internal network, while the nginx-tls-proxy service maps host port 443 to the container and uses custom configuration and certificates.

    Note: Ensure your OpenAPI specification file is available at the path specified in the volumes section of the prism service.

    version: '3.9'
    services:
      prism:
        image: stoplight/prism:4
        command: 'mock -h 0.0.0.0 /tmp/api.oas3.yml'
        volumes:
          - ./api.oas3.yml:/tmp/api.oas3.yml:ro
        networks:
          - prism
        expose:
          - '4010'
      nginx-tls-proxy:
        image: nginx:mainline
        volumes:
          # Override default config to act as TLS proxy
          - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
          # Self-signed certificates etc in here
          - ./tls:/etc/tls:ro
        depends_on:
          - prism
        networks:
          - prism
        ports:
          - '443:443'
    networks:
      prism:
  9. Mock a Postman Collection with Prism

    master

    Prism provides limited support for Postman Collections. You can use the prism mock command with a URL pointing to a Postman Collection JSON file (v2) to start a mock server. The workflow is identical to mocking an OpenAPI specification.

    prism mock https://raw.githubusercontent.com/postmanlabs/postman-collection/develop/examples/collection-v2.json
  10. Configure Static vs Dynamic response generation

    master

    Prism supports two modes of response generation:

    1. Static Generation (Default): Prism uses provided examples from the schema. If no examples exist, it generates a response based on the schema properties (using default values, example values, or type-based fallbacks like 'string' or 0).
    2. Dynamic Generation: Prism generates random values for all properties according to their type, format, or Faker definitions. This is useful for testing robust integrations with varying data.

    Commands:

    # Start in Static mode (default)
    prism mock api.oas3.yaml
    
    # Start in Dynamic mode
    prism mock -d api.oas3.yaml

    Note: If the server is running in static mode, you can trigger dynamic behavior for a specific call by sending the header Prefer: example=dynamic,true.

    prism mock -d api.oas3.yaml
  11. Configure Error Reporting in Validation Proxy

    master

    By default, the proxy reports violations in the sl-violations header without blocking the client. You can change this behavior using the --errors flag:

    • Default (No --errors flag): Violations are added to the sl-violations header. The request proceeds to the upstream server.
    • With --errors flag: Prism turns any request or response violation into an RFC 7807 HTTP Problem Details Error. The response body will contain the violation details, and the client will receive an error status (e.g., 422 Unprocessable Entity).
    prism proxy examples/petstore.oas2.yaml https://petstore.swagger.io/v2 --errors