I am using swagger-ui version 2.2.8
Our existing API can produce application/json as well as application/xml.
For a single record result in json it produces:
{
"person": {
"id": 23,
"name": "John"
}
}
and for XML it produces:
<person>
<id>23</id>
<name>John</name>
</person>
My swagger-schema for this is:
{
"person": {
"type": "object",
"properties": {
"person": {
"$ref": "#/definitions/personfields"
}
}
}
}
When viewed in swagger-ui the json model is looking fine. However the XML-model becomes:
<person>
<person>
<id>1</id>
<name>string</name>
</person>
</person>
Is there a way to prevent this double <person> but still get the correct JSON result?
In OpenAPI terms, your JSON and XML models are different – the JSON version of
<person>
<id>23</id>
<name>John</name>
</person>
would be
{
"id": 23,
"name": "John"
}
without the wrapper property person.
You can't have a single schema for models that differ in this way.
What you can do is define your model as a free-form object (type: object without properties) and specify the JSON/XML response examples instead – but in this case you lose the ability to define the object properties.
definitions:
person:
type: object
paths:
/person:
get:
produces:
- application/json
- application/xml
responses:
200:
description: OK
schema:
$ref: '#/definitions/person'
examples:
application/json: |
{
"person": {
"id": 23,
"name": "John"
}
}
application/xml: |
<person>
<id>23</id>
<name>John</name>
</person>
Note: If you use Swagger UI, use version 3.0.x becase 2.2.x does not display such examples correctly.
In the next version – OpenAPI 3.0 (which is RC at the moment of writing) – it will be possible to specify different schemas for different response MIME types. So in 3.0 your example will be described as:
paths:
/person:
get:
responses:
'200':
description: OK
content:
application/json:
$ref: '#/components/definitions/PersonJson'
application/xml:
$ref: '#/components/definitions/Person'
components:
definitions:
# XML object schema
Person:
type: object
properties:
id:
type: integer
example: 23
name:
type: string
example: John
xml:
name: person
# JSON object schema with a wrapper property "person"
PersonJson:
type: object
properties:
person:
$ref: '#/components/definitions/Person'
Related
Say I have an OpenAPI swagger.yml file that looks like:
openapi: '3.0.2'
info:
title: Simplest ever
version: '1.0'
servers:
- url: https://api.server.test/v1
paths:
/test:
get:
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
message:
type: string
I prefer to keep the source of truth schema in my schemas/ directory, for example schemas/get.json looks like:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"message": {
"type": "string"
}
}
}
The intent is for the schemas/*.json to used in my backend code base for validation for incoming and outgoing messages. Goal is to have strong API contracts.
What I don't understand is how to build the swagger.yml file using these JSON schema, instead of duplicating the work in YAML which is really tedious and error prone.
In OpenAPI 3.1, you can reference your JSON Schemas directly:
# openapi: 3.1.0
content:
application/json:
schema:
$ref: 'schemas/get.json'
Earlier OpenAPI versions expect that the JSON Schemas be converted to the OpenAPI Schema Object format (which can be represented as both YAML and JSON). The necessary changes include, for example:
removing unsupported keywords: $schema, patternProperties, and others;
replacing type: [<foo>, 'null'] with type: <foo> + nullable: true;
replacing other type arrays type: [type1, type2, ...] with oneOf/anyOf (OAS3) or removing them (OAS2).
json-schema-to-openapi-schema can automate the conversion.
You can try to $ref vanilla JSON Schemas directly from OAS 2.0 and 3.0 definitions, but some tools will error out on unexpected keywords and constructs.
I'm creating some API through swagger.
I can't understand how I can use $ref with a reference on the same file...
Here's my current swagger file:
openapi: 3.0.0
info:
title: test API
version: "1.0.0"
description: This is a sample API.
servers:
- url: http://api.internal.com/api
paths:
/sources/:
get:
summary: returns all sources given a page and a size
parameters:
- name: page
required: true
in: query
description: Limits the number of items on a page
schema:
type: integer
- name: size
required: true
in: query
description: Specifies a page size
schema:
type: integer
responses:
'200':
$ref: '#/definitions/myElement'
definitions:
myElement:
"data": {
"sources": [
{
"id": "fw5pQ08wMnFfbEE",
"fileName": "test.csv",
"size": 1000000,
"annotatedDate": "2018-10-01 12:00:00",
"metadataContact": "test#test.com",
"canBeIngested": true
}
],
"stats": {
"total": 4000,
"page": 1,
"size": 20
}
}
Now, the problem is that the editor is throwing me this error:
Errors
Schema error should NOT have additional properties
additionalProperty: definitions
Jump to line 0
in the documentation of $ref I can't really find anything helpful...
How can I fix this?
In OpenAPI 3.0, definitions were replaced with components/schemas. This means you need to use:
responses:
'200':
$ref: '#/components/schemas/myElement'
and
components:
schemas:
myElement:
...
Also, your model definition for myElement is not valid. See this guide to learn how to describe objects, properties, etc.
Currently my swagger output as a body parameter that looks like this
{
"name": "body",
"in": "body",
"description": "",
"required": true,
"type": "file"
}
and i read the documentation that the type property can be a array of types
{
"name": "body",
"in": "body",
"description": "",
"required": true,
"type": [null,"file"]
}
but I have found no way to tell aspnet core mvc or swaggerGen to output two types? Is this possible.
I would like the swaggerUI to include the option to either select a file or post some json data. Can this be done?
and i read the documentation that the type property can be a array of types
"type": [null,"file"]
This is not valid in OpenAPI/Swagger. type must be a single type, and there's no null type.
I would like the swaggerUI to include the option to either select a file or post some json data.
In OpenAPI/Swagger 2.0 this is not possible – an operation can post either a file or JSON but not both. You'll need two operations - one that accepts JSON, and another one that accepts a file.
What you want will be possible using OpenAPI 3.0. However, I don't know if ASP.NET Core MVC supports OpenAPI 3.0; it may take some time before tools adopt the new version of OpenAPI.
Your API spec (in YAML) would look like this:
paths:
/something:
post:
requestBody:
description: Either a file or JSON object
required: true
content:
application/json:
schema:
type: object:
properties:
...
# Post a file via a multipart request
multipart/form-data:
schema:
type: object
properties:
file: # <-- here "file" is a form field name
type: string
format: binary
required:
- file
# or maybe...
# Post a file directly
application/octet-stream:
schema:
type: string
format: binary
responses:
...
I want to construct an API gateway deployment from a swagger.yml file. I need to support CORS for all endpoints. All my options path definitions are exactly the same. How do I define the options path one place and $ref it where I want to use it?
I was hoping to do something like this (note the $ref: '#/definitions/CorsOptions' at the same level as get):
---
swagger: "2.0"
info:
version: "2016-10-26T03:15:31Z"
title: "corstest"
host: ""
basePath: ""
schemes:
- "https"
paths:
/page:
get:
produces:
- "application/json"
responses:
200:
description: "200 response"
schema:
$ref: "#/definitions/Empty"
headers:
Access-Control-Allow-Origin:
type: "string"
x-amazon-apigateway-integration:
responses:
default:
statusCode: "200"
responseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:1234:function:myLambdaFunc/invocations"
passthroughBehavior: "when_no_match"
httpMethod: "GET"
type: "aws_proxy"
$ref: '#/definitions/CorsOptions'
definitions:
Empty:
type: "object"
title: "Empty Schema"
CorsOptions:
options:
consumes:
- "application/json"
produces:
- "application/json"
responses:
200:
description: "200 response"
schema:
$ref: "#/definitions/Empty"
headers:
Access-Control-Allow-Origin:
type: "string"
Access-Control-Allow-Methods:
type: "string"
Access-Control-Allow-Headers:
type: "string"
Cache-Control:
type: "string"
x-amazon-apigateway-integration:
responses:
default:
statusCode: "200"
responseParameters:
method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
method.response.header.Access-Control-Allow-Origin: "'*'"
requestTemplates:
application/json: "{\"statusCode\": 200}"
passthroughBehavior: "when_no_match"
type: "mock"
This yaml does not pass swagger validation. How can I pull off what I'm trying to do so my yaml file is not huge and bloated with the same options path definition.
The swagger spec supports $ref as a path item object however I can't figure out where I can put that definition of the path item object. I think API Gateway swagger import restricts pulling yaml files from other places but I'm not 100% sure.
I don't think that will work. API Gateway currently only supports $ref for models and schemas, not for arbitrary objects. We have a backlog item to support $ref in more places, so we might add support for this eventually.
If you would like to specify $ref values in arbitrary places, you can use the expand-swagger-refs module.
This will take a Swagger schema as an input, and automatically inline all your $ref values, giving you back a schema that is suitable for use with API gateway.
It is available on the command line with support for stdin and stdout:
swagger-expand < my-complex-schema.json > aws-compatible.json
And also as an importable Node module:
const { expand, expanded } = require('expand-swagger-refs');
const schema = require('./api/swagger.json');
// Create a copy of the schema, with $ref values expanded:
const expandedSchema = expanded(schema);
// Or expand the schema object in-place (mutates the object):
expand(schema)
I am using Swagger to document my REST services. One of my services requires a CSV file to be uploaded. I added the following to the parameters section in my JSON API definition:
{
"name": "File",
"description": "The file in zip format.",
"paramType": "body",
"required": true,
"allowMultiple": false,
"dataType": "file"
}
and now I see the file upload option on my Swagger UI page. But when I select a file and click "try it out", I get the following error:
NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object in jquery-1.8.0.min.js (line 2)
The page is continuously processing and I am not getting any response.
Any ideas what could be wrong?
OpenAPI Specification 2.0
In Swagger 2.0 (OpenAPI Specification 2.0), use a form parameter (in: formData) with the type set to file. Additionally, the operation's consumes must be multipart/form-data.
consumes:
- multipart/form-data
parameters:
- name: file
in: formData # <-----
description: The uploaded file data
required: true
type: file # <-----
OpenAPI Specification 3.0
In OpenAPI Specification 3.0, files are defined as binary strings, that is, type: string + format: binary (or format: byte, depending on the use case). File input/output content is described with the same semantics as any other schema type (unlike OpenAPI 2.0):
Multi-part request, single file:
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
# 'file' will be the field name in this multipart request
file:
type: string
format: binary
Multi-part request, array of files (supported in Swagger UI 3.26.0+ and Swagger Editor 3.10.0+):
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
# The property name 'file' will be used for all files.
file:
type: array
items:
type: string
format: binary
POST/PUT file directly (the request body is the file contents):
requestBody:
content:
application/octet-stream:
# any media type is accepted, functionally equivalent to `*/*`
schema:
# a binary file of any type
type: string
format: binary
Note: the semantics are the same as other OpenAPI 3.0 schema types:
# content transferred in binary (octet-stream):
schema:
type: string
format: binary
Further information:
Considerations for File Uploads
Special Considerations for multipart Content
File Upload and Multipart Requests
finally i found answer for this, actually previously there is no support for file upload, now they updated swagger-ui.js file. You need to replace your old one with new and also you have to define these properties under Parameters for particular parameter:
"paramType": "body",
"dataType": "file",
Mine seems to work with
"paramType": "formData",
"dataType": "file",
I am using Open API v 3.0.3
Here's what my swagger.json looks like:
"/media/upload": {
"post": {
"tags": ["Media"],
"name": "Upload Media",
"description": "Uploads a Media file to the server.",
"requestBody": {
"required": true,
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"properties": {
"media": {
"type": "string",
"format": "base64"
}
}
}
}
}
}
}
}
Here's how it shows up in swagger: