Skip to content

Instantly share code, notes, and snippets.

@DilanLivera
Last active April 5, 2023 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DilanLivera/79026f3723a24bc576a568e86eb22979 to your computer and use it in GitHub Desktop.
Save DilanLivera/79026f3723a24bc576a568e86eb22979 to your computer and use it in GitHub Desktop.
Mocking HTTP APIs

Mocking HTTP APIs

Some people suggested Pact for API mocking. But it seems, Pact is a contract testing tool. According to Pact docs,

Pact is a code-first tool for testing HTTP and message integrations using contract tests. Contract tests assert that inter-application messages conform to a shared understanding that is documented in a contract. Without contract testing, the only way to ensure that applications will work correctly together is by using expensive and brittle integration tests.

Prism

The following is from Prism Docs: Overview, which describe what Prism does

Prism is a best in class Mock Server and Validation Proxy for OpenAPI documents and Postman Collections.

How to install

There are a few ways to install Prism. Prism docs include a detailed explanation of the process, which you can find at Prism Docs: Installation.

Mock an API document with Prism CLI

Prism CLI has two commands. One is mock, and the other is proxy. According to Prism Docs: Prism CLI: Proxy, proxy command

creates an HTTP server that will proxy all the requests to the specified upstream server. Prism will analyze the request coming in and the response coming back from the upstream server and report the discrepancies with what's declared in the provided OpenAPI document.

We need to use the mock command to mock an API document.

#using a hosted api document
prism mock https://raw.githack.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml

#using an api document in local machine
prism mock C:\apis\petstore.oas2.yaml

We can use the following parameters with the prism mock command:

Parameter Description Type
--version Show version number [boolean]
--help Show help [boolean]
-p, --port Port that Prism will run on [number] [required] [default: 4010]
-h, --host Host that Prism will listen to [string] [required] [default: "127.0.0.1"]
--cors Enables CORS headers [boolean] [default: true]
-m, --multiprocess Forks the http server from the CLI for faster log processing [boolean] [default: false]
--errors Specifies whether request/response violations marked as errors will produce an error response [boolean] [required] [default: false]
-d, --dynamic Dynamically generate examples [boolean] [default: false]

After starting the mock server you can call the path in the API document by appending the path to the http://localhost.4010 base URL(e.g. http://localhost.4010/api/v3/store/order/123), assuming you used the default host and port. The mock server will return the 200 OK response if the request is valid.

Retrieve an example for an endpoint

According to Prism Docs: HTTP Mocking: Response Generation

Prism will try to return meaningful responses based on whatever information it has available, like response examples, and use various fallback mechanisms in case no examples were provided. This means any OpenAPI description document can be used with no extra work, but better documents provide better results.

To get a specific response example from the API document, we can use the Prefer header parameter with the example value.

postman request with the prefer header for getting an example in the api document

Dynamic response generation

For Prism to return dynamic responses for the request, we need to add the prefer header with the dynamic=true value.

postman request with a dynamic response

Please find more info at Prism Docs: HTTP Mocking: Response Generation: Static or Dynamic Generation.

Request Validation

We can use the --errors parameter to retrieve any validation errors in the request. If there are any validation errors, Prism mock will,

  • return 400 Bad Request response if the path contains a 400 response. During my testing of this functionality, I also saw a header named sl-violations in the response with an array of errors similar to the following.

    [
      {
        "location": ["request", "body"],
        "severity": "Error",
        "code": "required",
        "message": "must have required property 'name'"
      }
    ]

    prism log for the bad request

  • return the 422 Unprocessable Entity response if the path does not contain a 400 response. The response will contain information about the error/s in the response body. E.g.

    {
      "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": ["body"],
          "severity": "Error",
          "code": "required",
          "message": "must have required property 'name'"
        }
      ]
    }

    prism log for the bad request

Note: During my local testing I was getting the same behaviour as above for validation errors with or without the --errors parameter.

Please refer to Prism Docs: Errors page to find more information about the errors(e.g. UNPROCESSABLE_ENTITY, NO_BASE_URL_ERROR) Prism returns.

Please find more info at Prism Docs: Request Validation.

Mocking Callbacks with Prism

Please find more info at Prism Docs: Mocking Callbacks with Prism.

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment