I'm preparing my API documentation by doing it per hand and not auto generated. There I have headers that should be sent to all APIs and don't know if it is possible to define parameters globally for the whole API or not?
Some of these headers are static and some has to be set when call to API is made, but they are all the same in all APIs, I don't want to copy and paste parameters for each API and each method as this will not be maintainable in the future.
I saw the static headers by API definition but there is no single document for how somebody can set them or use them.
Is this possible at all or not?
It depends on what kind of parameters they are.
The examples below are in YAML (for readability), but you can use http://www.json2yaml.com to convert them to JSON.
Security-related parameters: Authorization header, API keys, etc.
Parameters used for authentication and authorization, such as the Authorization header, API key, pair of API keys, etc. should be defined as security schemes rather than parameters.
In your example, the X-ACCOUNT looks like an API key, so you can use:
swagger: "2.0"
...
securityDefinitions:
accountId:
type: apiKey
in: header
name: X-ACCOUNT
description: All requests must include the `X-ACCOUNT` header containing your account ID.
# Apply the "X-ACCOUNT" header globally to all paths and operations
security:
- accountId: []
or in OpenAPI 3.0:
openapi: 3.0.0
...
components:
securitySchemes:
accountId:
type: apiKey
in: header
name: X-ACCOUNT
description: All requests must include the `X-ACCOUNT` header containing your account ID.
# Apply the "X-ACCOUNT" header globally to all paths and operations
security:
- accountId: []
Tools may handle security schemes parameters differently than generic parameters. For example, Swagger UI won't list API keys among operation parameters; instead, it will display the "Authorize" button where your users can enter their API key.
Generic parameters: offset, limit, resource IDs, etc.
OpenAPI 2.0 and 3.0 do not have a concept of global parameters. There are existing feature requests:
Allow for responses and parameters shared across all endpoints
Group multiple parameter definitions for better maintainability
The most you can do is define these parameters in the global parameters section (in OpenAPI 2.0) or the components/parameters section (in OpenAPI 3.0) and then $ref all parameters explicitly in each operation. The drawback is that you need to duplicate the $refs in each operation.
swagger: "2.0"
...
paths:
/users:
get:
parameters:
- $ref: '#/parameters/offset'
- $ref: '#/parameters/limit'
...
/organizations:
get:
parameters:
- $ref: '#/parameters/offset'
- $ref: '#/parameters/limit'
...
parameters:
offset:
in: query
name: offset
type: integer
minimum: 0
limit:
in: query
name: limit
type: integer
minimum: 1
maximum: 50
To reduce code duplication somewhat, parameters that apply to all operations on a path can be defined on the path level rather than inside operations.
paths:
/foo:
# These parameters apply to both GET and POST
parameters:
- $ref: '#/parameters/some_param'
- $ref: '#/parameters/another_param'
get:
...
post:
...
If you're talking about header parameters sent by consumer when calling the API...
You can at least define them once and for all in parameters sections then only reference them when needed.
In the example below:
CommonPathParameterHeader, ReusableParameterHeader and AnotherReusableParameterHeader are defined once and for all in parameterson the root of the document and can be used in any parameters list
CommonPathParameterHeaderis referenced in parameters section of /resources and /other-resources paths, meaning that ALL operation of these paths need this header
ReusableParameterHeader is referenced in get /resources meaning that it's needed on this operation
Same thing for AnotherReusableParameterHeader in get /other-resources
Example:
swagger: '2.0'
info:
version: 1.0.0
title: Header API
description: A simple API to learn how you can define headers
parameters:
CommonPathParameterHeader:
name: COMMON-PARAMETER-HEADER
type: string
in: header
required: true
ReusableParameterHeader:
name: REUSABLE-PARAMETER-HEADER
type: string
in: header
required: true
AnotherReusableParameterHeader:
name: ANOTHER-REUSABLE-PARAMETER-HEADER
type: string
in: header
required: true
paths:
/resources:
parameters:
- $ref: '#/parameters/CommonPathParameterHeader'
get:
parameters:
- $ref: '#/parameters/ReusableParameterHeader'
responses:
'200':
description: gets some resources
/other-resources:
parameters:
- $ref: '#/parameters/CommonPathParameterHeader'
get:
parameters:
- $ref: '#/parameters/AnotherReusableParameterHeader'
responses:
'200':
description: gets some other resources
post:
responses:
'204':
description: Succesfully created.
If you're talking about header sent with each API response...
Unfortunately you cannot define reusable response headers.
But at least you can define a reusable response containing these headers for common HTTP responses such as a 500 error.
Example:
swagger: '2.0'
info:
version: 1.0.0
title: Header API
description: A simple API to learn how you can define headers
parameters:
CommonPathParameterHeader:
name: COMMON-PARAMETER-HEADER
type: string
in: header
required: true
ReusableParameterHeader:
name: REUSABLE-PARAMETER-HEADER
type: string
in: header
required: true
AnotherReusableParameterHeader:
name: ANOTHER-REUSABLE-PARAMETER-HEADER
type: string
in: header
required: true
paths:
/resources:
parameters:
- $ref: '#/parameters/CommonPathParameterHeader'
get:
parameters:
- $ref: '#/parameters/ReusableParameterHeader'
responses:
'200':
description: gets some resources
headers:
X-Rate-Limit-Remaining:
type: integer
X-Rate-Limit-Reset:
type: string
format: date-time
/other-resources:
parameters:
- $ref: '#/parameters/CommonPathParameterHeader'
get:
parameters:
- $ref: '#/parameters/AnotherReusableParameterHeader'
responses:
'200':
description: gets some other resources
headers:
X-Rate-Limit-Remaining:
type: integer
X-Rate-Limit-Reset:
type: string
format: date-time
post:
responses:
'204':
description: Succesfully created.
headers:
X-Rate-Limit-Remaining:
type: integer
X-Rate-Limit-Reset:
type: string
format: date-time
'500':
$ref: '#/responses/Standard500ErrorResponse'
responses:
Standard500ErrorResponse:
description: An unexpected error occured.
headers:
X-Rate-Limit-Remaining:
type: integer
X-Rate-Limit-Reset:
type: string
format: date-time
About OpenAPI (fka. Swagger) Next version
The OpenAPI spec (fka. Swagger) will evolve and include the definition of reusable response headers among other things (cf. https://github.com/OAI/OpenAPI-Specification/issues/563).
As per this Swagger issue comment, support for global parameters (including header parameters) is not planned in foreseeable future, but to limit the repetition you should use parameters references as in #Arnaud's answer (parameters: - $ref: '#/parameters/paramX').
also wish some global variables, can be used anywhere.
( even in some examples, so can change common settings globally in ui ).
something like
"hello ${var1}" in shell or javascript.
searched docs many times, not found solution yet.
: (
Related
I'm having problems defining custom request headers for my OpenAPI (Swagger) document. I've looked in the documentation https://swagger.io/docs/specification/describing-parameters/#header-parameters but I cannot get it to work.
In my example below is a POST request which has has a body. I also want it to have a custom header like my second snippet, but that is not valid.
This is OK:
/search:
post:
tags:
- Domain
summary: Search for domains
description: Returns a domain if it was found.
produces:
- application/json
parameters:
- in: body
name: body
description: Array of Domain Names
required: true
schema:
$ref: '#/definitions/DomainNames'
This is not OK:
/search:
post:
tags:
- Domain
summary: Search for domains
description: Returns a domain if it was found.
produces:
- application/json
parameters:
- in: header
name: X-Request-ID
schema:
type: string
format: uuid
required: true
- in: body
name: body
description: Array of Domain Names
required: true
schema:
$ref: '#/definitions/DomainNames'
On the - in: header line I get the following error:
Schema error at paths['/search'].post.parameters[0].in
should be equal to one of the allowed values
allowedValues: body, header, formData, query, path
Jump to line 37
Schema error at paths['/search'].post.parameters[0]
should NOT have additional properties
additionalProperty: schema, in, name
Jump to line 37
What am I missing here? The header shows up in the rendered Swagger UI but I can't "Save" it as it is not valid.
The guide you linked to is for OpenAPI 3.0 (as indicated at the top of that page). The corresponding OpenAPI 2.0 guide is here: Describing Parameters.
In OpenAPI 2.0, path/header/query/form parameters do not use schema, they use the type keyword directly.
Also, the - in: header line in your example is not indented enough, you need to add one more space before it to align it with other lines.
Here's the correct version:
parameters:
- in: header # <----
name: X-Request-ID
type: string # <----
format: uuid # <----
required: true
I'm writing an Open API 3.0 spec and trying to get response links to render in Swagger UI v 3.18.3.
Example:
openapi: 3.0.0
info:
title: Test
version: '1.0'
tags:
- name: Artifacts
paths:
/artifacts:
post:
tags:
- Artifacts
operationId: createArtifact
requestBody:
content:
application/octet-stream:
schema:
type: string
format: binary
responses:
201:
description: create
headers:
Location:
schema:
type: string
format: uri
example: /artifacts/100
content:
application/json:
schema:
type: object
properties:
artifactId:
type: integer
format: int64
links:
Read Artifact:
operationId: getArtifact
parameters:
artifact-id: '$response.body#/artifactId'
/artifacts/{artifact-id}:
parameters:
- name: artifact-id
in: path
required: true
schema:
type: integer
format: int64
get:
tags:
- Artifacts
operationId: getArtifact
responses:
200:
description: read
content:
application/octet-stream:
schema:
type: string
format: binary
renders a link like this:
Is this expected? I ask because the operationId is exposed on the UI and parameters is shown as a JSON reference make it seem like something is not displaying properly. I would have expected a hyperlink or something to take me to the appropriate section in the Swagger web page that corresponds to the API being referenced by the link.
Yes this is how Swagger UI currently renders OAS3 links. Rendering of links is one of the things on their OAS3 support backlog:
OAS 3.0 Support Backlog
This is a collection ticket for OAS3 specification features that are not yet supported by Swagger-UI.
...
[ ] Links can't be used to stage another operation
[ ] Link-level servers are not available for executing requests
I have a swagger file for an API that is going to reside inside IBM API Connect. I typed it out from an IBM tutorial, and I was trying to replicate what the instructor was doing(he did not provide any source files, so I had to type it out).
The tutorial is available here: https://www.youtube.com/watch?v=hCvUYd67rbI
The guy is copy-pasting the swagger file inside the APIConnect local designer around 21:40.
I took the swagger file and put it into http://editor.swagger.io/ and I got a bunch of parser errors:
Errors
Hide
Parser error duplicated mapping key
Jump to line 31
Semantic error at definitions.shipping.properties.xyz.type
Sibling values are not allowed alongside $refs
Jump to line 86
Semantic error at definitions.shipping.properties.cek.type
Sibling values are not allowed alongside $refs
Jump to line 89
I did some digging, and I did not find a lot of resources for my kind of problem. I double-checked if I typed it out correctly from the tutorial. Maybe it has something to do with an older version of API Connect being used in ths tutorial.
Thanks in advance for anyone who can help.
EDIT:
Sorry, it was a bit late so I was tired, I am adding the source code in the yaml file:
info:
x-ibm-name: logistics
title: logistics
version: 1.0.0
schemes:
- https
basePath: /logistics
consumes:
- application/json
produces:
- application/json
securityDefinitions:
clientIdHeader:
type: apiKey
in: header
name: X-IBM-Client-Id
security:
- clientdHeader: []
x-ibm-configuration:
testable: true
enforced: true
cors:
enabled: true
gateway: datapower-gateway
catalogs:
apic-dev:
properties:
runtime-url: $(TARGET_URL)
properties:
shipping_svc_url:
value: 'http://shipping.think.ibm:5000/calculate'
description: Location of the shipping calculator service
encoded: false
paths:
/shipping:
get:
responses:
'200':
description: 200 OK
schema:
$ref: '#/definitions/shipping'
summary: Calculate shipping costs to a destination zip code
operationId: shipping.calc
parameters:
- name: zip
type: string
required: true
in: query
description: Destination zip code.
/stores:
get:
responses:
'200':
description: 200 OK
schema:
$ref: '#/definitions/store_location'
tags:
- stores
summary: Locate store near zip code
operationId: get.stores
parameters:
- name: zip
type: string
required: true
in: query
definitions:
rates:
properties:
next_day:
type: string
example: '20.00'
two_day:
type: string
example: '17.00'
ground:
type: string
example: '8.00'
required:
- two_day
- next_day
- ground
shipping:
properties:
xyz:
type: string
$ref: '#/definitions/rates'
cek:
type: string
$ref: '#/definitions/rates'
required:
- xyz
- cek
store_location:
properties:
google_maps_link:
type: string
example: 'https://www.google.com/maps?q=34.1030032,-118.4104684'
required:
- google_maps_link
There's typo: securityDefinitions defines clientIdHeader, but security refers to clientdHeader (..ntd.. instead of ..enId..).
"Sibling values are not allowed alongside $refs" is not a syntax error, but rather a warning. It's caused by this line:
definitions:
rates:
properties:
...
shipping:
properties:
xyz:
type: string # <---------------
$ref: '#/definitions/rates'
$ref is a JSON Reference, it works by replacing itself and all sibling attributes with the content the $ref is pointing at. So, the type attribute and any other attributes alongside $ref will be ignored. The warning informs you about this in case there are important attributes alongside $ref -- these attributes need to be moved into the $ref'erenced schema to have effect.
That said, xyz being type: string does not make sense, because rates is an object and not a string.
You should also consider adding type: object to the rates, shipping and store_location definitions to indicate that they are objects.
I'm looking for an elegant way to define an api that can consume JSON data as well as form data. The following snippet works, but it's not elegant and requires all kind of ugly code in the backend. Is there a better way to define this?
What works right now:
paths:
/pets:
post:
consumes:
- application/x-www-form-urlencoded
- application/json
parameters:
- name: nameFormData
in: formData
description: Updated name of the pet
required: false
type: string
- name: nameJSON
in: body
description: Updated name of the pet
required: false
type: string
Basic idea of how I'd like it to work:
paths:
/pets:
post:
consumes:
- application/x-www-form-urlencoded
- application/json
parameters:
- name: name
in:
- formData
- body
description: Updated name of the pet
required: true
type: string
But this doesn't work because the in value must be a string, not an array.
Any good ideas?
OpenAPI 2.0
In OpenAPI 2.0, there's no way to describe that. Form and body parameters are mutually exclusive, so an operation can have either form data OR JSON body but not both. A possible workaround is to have two separate endpoints - one for form data and another one for JSON - if that is acceptable in your scenario.
OpenAPI 3.0
Your scenario can be described using OpenAPI 3.0. The requestBody.content.<media-type> keyword is used to define various media types accepted by the operation, such as application/json and application/x-www-form-urlencoded, and their schemas. Media types can have the same schema or different schemas.
openapi: 3.0.0
...
paths:
/pets:
post:
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
application/x-www-form-urlencoded:
schema:
$ref: '#/components/schemas/Pet'
responses:
'200':
description: OK
components:
schemas:
Pet:
type: object
properties:
name:
type: string
description: Updated name of the pet
required:
- name
Further info:
OAS3: Describing Request Body
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#support-for-x-www-form-urlencoded-request-bodies
https://blog.readme.io/an-example-filled-guide-to-swagger-3-2/#requestformat
I am starting a REST service, using Swagger Codegen. I need to have different responses for different parameters.
Example: <baseURL>/path can use ?filter1= or ?filter2=, and these parameters should produce different response messages.
I want my OpenAPI YAML file to document these two query params separately. Is this possible?
It is not supported in the 2.0 spec, and not in 3.0 either.
Here are the corresponding proposals in the OpenAPI Specification repository:
Accommodate legacy APIs by allowing query parameters in the path
Querystring in Path Specification
If you're still looking, I found out a way around this problem. It's a bit of a hack, but it works.
Basically, you can have two definitions to the same path by adding a slash (/) in the URL.
That way, you can set a response for <baseURL>/path with the ?filter1= parameter and set another response for <baseURL>//path with the ?filter2= parameter. It's also important that you give an unique operationId for each of the definitions.
paths:
/path/you/want:
get:
summary: Test
operationId: get1
parameters:
- name: filter1
type: string
in: path
required: true
responses:
200:
description: Successful response
schema:
$ref: '#/definitions/SomeResponse'
/path/you//want:
get:
summary: Another test
operationId: get2
parameters:
- name: filter2
type: string
in: path
required: true
responses:
200:
description: Successful response
schema:
$ref: '#/definitions/SomeOtherResponse'
I tried this with a path parameter and it worked just fine!
In swagger defining location,type explicitly is what defines these variables.
You have all the required fields to avoid collision of variables, for a json body you have to reference a declaration or use an example schema as shown below. For my case I have used a schema example rather than a declaration reference
/auth/account/password/reset/{userId}/{resetToken}:
post:
consumes:
- application/json
parameters:
- in: path
name: userId
type: string
required: true
- in: path
type: string
name: resetToken
required: true
- in: header
name: authorization
required: true
type: string
- in: body
name: body
required: true
schema:
type: object
example:
password: password
confirmPassword: password
responses:
"200":
description: OK
In Swagger you can add ? to make endpoints different.
i.e. /articles and /articles?:
When using ? in Swagger editor you will see error:
However on your final Swagger page there will be mark VALID
Additional information:
Remember about unique operationId for duplicated entries