How can I have multiple responses from a single endpoint with different parameters?

8.2k Views Asked by At

We are looking at using the API Blueprint. There are cases where we would like one request to return a proper response and another request to return an 'error' response such as a 400 bad request so that other developers can work against the mock API on apiary.io with both types of responses and handle it in their applications.

I've created a completely arbitrary example below,

## Thing [/thing/{id}]
Gets a thing but the thing id must be a prime number!


+ Parameters
    + id (string) ... ID of the thing, a prime number!

+ Model (application/json)

    The thing itself.

    + Body

            {
                "description": "It is green"
            }

### Retrieve a Single Gist [GET]
+ Response 200

    [Gist][]

Now somehow I would like to add in a response for /thing/40

+ Response 400
    {  "error" : "Invalid request" }

But I am not sure how I would do this with the API Blueprint. This was achievable under the 'old' style on apiary.io but we'd like to move on to the new syntax

2

There are 2 best solutions below

4
On

To document multiple responses simply add it after the Response 200 like so:

## Thing [/thing/{id}]
Gets a thing but the thing id must be a prime number!

+ Parameters
    + id (string) ... ID of the thing, a prime number!

+ Model (application/json)

    The thing itself.

    + Body

            {
                "description": "It is green"
            }

### Retrieve a Single Gist [GET]
+ Response 200

    [Thing][]

+ Response 400 (application/json)

        {  "error" : "Invalid request" }

Note there is currently no dedicated syntax to discuss the conditions (when this response i s returned). You can discuss it anyway you like it for example:

+ Response 400 (application/json)

    This response is returned when no `Thing` for given `id` exists.

    + Body

If you are using Apiary mock, keep in mind that the first response listed is returned by default, unless you say otherwise using the prefer HTTP header.

0
On

You can use the templates and specify a specific use case after a generic response for your resource, see example:

Reservation [/reservation/{reservation_key}]

A Reservation object has the following attributes:

  • room_number
  • reserved_at - An ISO8601 date when the question was published.
  • booker_details - A Booker Object.

  • Parameters

    • reservation_key (required, text, 1) ... Reservation Key ash

View a Reservation Detail [GET]

  • Response 200 (application/json)

    {
        "room_number": 55,
        "reserved_at": "2014-11-11T08:40:51.620Z",
        "booker_details": 
            {
                "name": "Jon",
                "last_name": "Doe",
            }
    }
    

Reservation [/reservation/notarealreservation123]

Using a non existing reservation (pls use notarealreservation123 in the fake) returns not found