How to define custom response header for all responses


#1

For my API all requests must contain the X-Sample-Request-Header and all responses must contain the X-Sample-Response-Header. I am able to handle the request header by using a trait but the only way I’ve found to handle the response header is to repeat the markup for every response code. Is there a way to remove this markup duplication?


#2

I think you can also use traits to define responses. For instance we create an external YAML file with the following content:

commonErrorResponseCompliant:
  responses:
    400:
      description: Bad request, check request's parameters
      body:
        application/json:
          example: | 
            {
              result: {
                code: 400,
                info: "Bad Request" 
              }
            }
        text/xml:
          example: |
            <response>
              <result>
                <code>400</code>
                <info>Bad Request</info>
                </result>
            </response>
        text/plain:
          example: |
            BAD REQUEST
    401:
      description: Unathorized, invalid app_id and/or app_key
      body:
        application/json:
          example: |
            {
              result: {
                code: 401,
                info: "Unauthorized" 
              }
            }
        text/xml:
          example: |
            <response>
              <result>
                <code>401</code>
                <info>Unauthorized</info>
              </result>
            </response>
        text/plain:
          example: | 
            UNAUTHORIZED

and include it on the traits section

traits:
 - !include commons/errors.yaml

and then we use the trait on each resource on the “is” section.

  /basic_stats:
     is: [commonErrorResponseCompliant]

#3

@luix yes what you posted is good however my “problem” is that the trait is actually defining the responses for the endpoint and not all endpoints have the same responses.

For example a request like GET /widgets could respond with a 200 or a 500 while a request like POST /widgets could respond with a 201, 400, 422 or 500.

It looks like I’m going to have to handle this in the resourceTypes section. Which feels weird to me it definitely feels like it should be a trait.


#4

I still think you can do it with traits.

You can define 2 traits with separate sets of responses, one for the get (200 500) and a second (o third or fourth…) with the POST responses (201 402 …).

The point is to use traits to increase readability and !includes to te reuse everything (responses, qparams, uriparams ., headers,.)


#5

Okay after some more playing I see what you mean. :penguin: