40

In OpenAPI (Swagger) 2.0, we could define header parameters like so:

paths:
  /post:
    post:
      parameters:
        - in: header
          name: X-username

But in OpenAPI 3.0.0, parameters are replaced by request bodies, and I cannot find a way to define header parameters, which would further be used for authentication.

What is the correct way to define request headers in OpenAPI 3.0.0?

Helen
  • 87,344
  • 17
  • 243
  • 314
kritika agarwal
  • 505
  • 1
  • 6
  • 11

1 Answers1

55

In OpenAPI 3.0, header parameters are defined in the same way as in OpenAPI 2.0, except the type has been replaced with schema:

paths:
  /post:
    post:
      parameters:
        - in: header
          name: X-username
          schema:
            type: string

When in doubt, check out the Describing Parameters guide.

But in Swagger 3.0.0 parameters are replaced by request bodies.

This is only true for form and body parameters. Other parameter types (path, query, header) are still defined as parameters.

define header parameters, which would further be used for authentication.

A better way to define authentication-related parameters is to use securitySchemes rather than define these parameters explicitly in parameters. Security schemes are used for parameters such as API keys, app ID/secret, etc. In your case:

components:
  securitySchemes:
    usernameHeader:
      type: apiKey
      in: header
      name: X-Username

paths:
  /post:
    post:
      security:
        - usernameHeader: []
      ...
Helen
  • 87,344
  • 17
  • 243
  • 314
  • But this API is to send the username and password to a third party for authenticating the login and in return sends the token ID which I would further use in bearer authentication value for other APIs, would that still be a good idea to add in component? – kritika agarwal May 01 '18 at 14:54
  • 2
    It's up to you really. I would define [Bearer auth as a security scheme](https://stackoverflow.com/a/45471010/113116) but the initial login request with regular parameters. – Helen May 01 '18 at 14:59
  • 1
    That's what I did and yes it worked for me, thanks Helen, instant help appreciated.. – kritika agarwal May 01 '18 at 15:14
  • 2
    I need to pass in something like `Usage-Data: kind=sdk, name=nodejs, version=1.2.3` via the header. This never changes and I want it to be sent on all requests for all paths. How can I do this? @Helen – Rodrigo Gomez-Palacio Sep 24 '21 at 22:47
  • @RodrigoGomez-Palacio please [ask a new question](/questions/ask?tags=openapi). – Helen Sep 25 '21 at 10:51