Swagger Swashbuckle not showing response object in swagger.json - swagger

swagger 2.0.
.netcore 2.1
swashbuckle as in the image.
I have this attribute on an api endpoint:
[SwaggerResponse(statusCode: 200, type: typeof(List<Cat>), description: "successful operation")]
When I run the API and navigate to https://localhost:44394/swagger/v1/swagger.json the json is there but the SwaggerResponse seems to be being ignored.
This is an example of what I receive:
"/api/data/cats": {
"get": {
"tags": [
"CatApi"
],
"operationId": "GetCatsById",
"consumes": [],
"produces": [],
"parameters": [
{
"name": "catIds",
"in": "query",
"required": true,
"type": "array",
"items": {
"type": "integer",
"format": "int32"
},
"collectionFormat": "multi",
"uniqueItems": false
}
],
"responses": {
"200": {
"description": "Success"
}
}
}
},
You can see that the response just show a 200 and I'm not exactly sure where it's getting that description from - as you can see in the attribute it should be successful operation and my XML comment is <response code="200">successful operation</response>.
I'm very confused. How can I get Swashbuckle it use the SwaggerResponse attribute when it generates the json?
More info:
If I use [ProducesResponseType(statusCode: 200, type: typeof(List<Cat>))] then I get what I want:
"/api/data/cats": {
"get": {
"tags": [
"CatsApi"
],
"operationId": "GetCatsById",
"consumes": [],
"produces": [
"text/plain",
"application/json",
"text/json"
],
"parameters": [
{
"name": "catIds",
"in": "query",
"required": true,
"type": "array",
"items": {
"type": "integer",
"format": "int32"
},
"collectionFormat": "multi",
"uniqueItems": false
}
],
"responses": {
"200": {
"description": "Success",
"schema": {
"uniqueItems": false,
"type": "array",
"items": {
"$ref": "#/definitions/Cat"
}
}
}
}
}
},
You can see the additional data in the produces field and the schema in the responses field.
I could change to use ProducesResponseType everywhere but it isn't a standard field as far as Swagger is concerned - if I ever regenerate the code from the swagger file then I'll have to always make these changes so I'd like to get it working with SwaggerResponse.

Step 1: Double check if your are missing the Swagger Decorator Attributes, follow this below and replace the attributes with your specific Types / MyModel
Since you didn't put up your actual code, to see how it works, use the default samples for e.g. you can Install my Swashbuckle.Examples NuGet package. Decorate your methods with the new SwaggerResponseExample attributes below and you will see it work just fine!
// These attributes will help with your nested objects
[SwaggerResponse(HttpStatusCode.OK, Type=typeof(IEnumerable<Country>))]
[SwaggerResponseExample(HttpStatusCode.OK, typeof(CountryExamples))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(IEnumerable<ErrorResource>))]
public async Task<HttpResponseMessage> Get(string lang)
Ste 2: Also ensure you have it configured like so
configuration
.EnableSwagger(c =>
{
c.OperationFilter<ExamplesOperationFilter>();
})
.EnableSwaggerUi();

Also make sure you have the right using for the annotations. I searched and searched because the SwaggerResponse were missing and i couldn't get my head behind it.
I somehow managed to use Nswag Annotations, but needed Swashbucke using:
using Swashbuckle.AspNetCore.Annotations;
I think it came because as i didn't have a nuget for SwaggerResponse installed and the first suggestion for a nuget package that has this type was nswag.

Related

Postman: "Invalid data type. Must be either, array, boolean, number" error

I get the following error when creating API in Postman: "Invalid data type. Must be either, array, boolean, integer, number, object or string"
The error is fixed when converting the line "type": "file" to "type": "object", but I am not sure if there is a proper way for this situation. Because with this update, the request may not be passed when sending request in Postman.
"parameters": [
{
"in": "body",
"name": "file",
"description": "file",
"required": false,
"schema": {
"type": "array",
"items": {
"type": "file"
}
}
},
...
]
So, how can I fix the problem in Postman?
The problem is not with Postman, but with the API definition. "type": "file" is not a valid type value for use in schemas and body parameters, this type can only be used in in: formData parameters.
On the other hand, I do not add file while trying to test my app via Postman. For this reason, I just want to suppress the errors
In this case you could change "type": "file" to "type": "string" to suppress import errors. Or remove the entire problematic operation from the API definition.
How to properly define file uploads in OpenAPI
The API definition is trying to describe uploading of a file array - but this is not supported in OpenAPI 2.0 (swagger: '2.0'). OAS2 only supports upload of individual named files via multipart/form-data, in which case the API definition would look like this:
{
"swagger: "2.0",
...
"paths": {
"/something": {
"post": {
"consumes": [
"multipart/form-data"
],
"parameters": [
{
"in": "formData",
"name": "file1",
"type": "file" // A single file sent via form field "file1"
},
{
"in": "formData",
"name": "file2",
"type": "file" // Another file sent via form field "file2"
}
]
...
}
Uploading an array of files is supported in OpenAPI 3 though:
{
"openapi": "3.0.0",
...
"paths": {
"/something": {
"post": {
"requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"properties": {
"file": {
"type": "array",
"items": {
"type": "string",
"format": "binary"
}
}
}
}
}
}
},
...
}
}
}
}

How to use the spec url parameter of the swagger editor

I'm trying to pass the spec parameter in the url to the swagger editor to be able to open the API spec passed in the URL
https://editor.swagger.io/?spec={...}
as documented here:
https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/
spec SPEC Object={}. A JavaScript object describing the OpenAPI definition. When used, the url parameter will not be parsed. This is useful for testing manually-generated definitions without hosting them.
but it seems that doesn't work, here the example
below the spec put in the link:
{
"openapi": "3.0.0",
"info": {
"version": "1.0.0",
"title": "Swagger"
},
"paths": {
"/mypath": {
"get": {
"operationId": "listPets",
"parameters": [
{
"name": "limit",
"in": "query",
"required": false,
"schema": {
"type": "integer",
"format": "int32"
}
}
],
"responses": {
"200": {
"description": "A paged array of pets"
}
}
}
}
}
}

Swagger API Special character issue

I am new in swagger and want to deploy an API which is having query string. This is the API I am getting encoded URL after passing the parameter in the GET method.
API URL with Parameter should be:-
baseurl/v1/auth/getOTP?email=somename#email.com
but I am getting something like:-
baseurl/v1/auth/getOTP?email=somename%40email.com
what I have tried is:-
"/auth/getOTP": {
"get": {
"tags": [
"pet"
],
"summary": "",
"description": "",
"operationId": "findPetsByStatus",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "email",
"in": "path",
"description": "",
"required": true,
"type": "string",
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
Swagger OpenAPI has Specified: in this GitHub Issue-1840, It is specifically disallowed on in: path parameters for the same reason they don't allow optional path parameters, e.g. {/foo} By having variable path segments it become difficult to resolve a URL to an operation.
If you want to use some kind of hack then follow this GitHub Issue-230.
If you really needed then Its support in in: query parameters, as below,
The allowReserved keyword specifies whether the reserved characters :/?#[]#!$&'()*+,;= in parameter values are allowed to be sent as they are, or should be percent-encoded. By default, allowReserved is false, and reserved characters are percent-encoded.
Here you need to set it to true,
"parameters": [
{
"name": "email",
"in": "query",
"description": "",
"required": true,
"type": "string",
"allowReserved": true
}
],
Look at the Example Swagger Describing Parameters
and For more details follow Swagger Serialization.

Building an OpenAPI response, including oneOf, and maybe allOf

I am trying to build up a response from a variety of schema components using OpenAPI 3. There are basically three parts to the response:
A shared component that other endpoints use (i.e. success/failure flags). - #/components/schemas/core_response_schema inside allOf.
Properties that all responses on this endpoint use (i.e., user_id) - the properties component of the below.
One of several schemas that will vary depending on the type of user. - the oneOf component.
I've determined that I have to use allOf to be able to mix properties (item 2) and the core response (item 1), though this feels wrong as there's only one item. I tried a $ref, but it didn't work.
The below successfully passes three different OpenAPI linting tools, but in the example it builds, Swagger UI does not show the item 2 things (properties), and does show all of the item 3 things (should be oneOf).
"responses": {
"200": {
"description": "Operation successfully executed.",
"content": {
"application/json": {
"schema": {
"properties": {
"user_id": {
"$ref": "#/components/schemas/user_id"
},
"results": {
"type": "array",
"items": {
"$ref": "#/components/schemas/result_user_by_id"
}
}
},
"type": "object",
"allOf": [
{
"$ref": "#/components/schemas/core_response_schema"
}
],
"oneOf": [
{
"$ref": "#/components/schemas/user_type_a"
},
{
"$ref": "#/components/schemas/user_type_b"
},
{
"$ref": "#/components/schemas/user_type_c"
}
]
}
}
}
}
},
"components": {
"schemas": {
"core_response_schema": {
"properties": {
"success": {
"description": "A flag indicating whether the request was successfully completed or not.",
"type": "boolean"
},
"num_results": {
"description": "The number of results for this request",
"type": "integer"
}
},
"type": "object"
},
"user_id": {
"description": "Unique 10 character `user_id`.",
"type": "string",
"maxLength": 10,
"minLength": 10,
"example": "a1b2c3d4e5"
},
}
}
And example payloads for two users. Type A and B (it's a contrived example).
User Type A:
{
"success": true,
"num_results": 1,
"user_id": "c1b00cb714",
"results": [{
"user_type": "a",
"group_id": "e7a99e3769",
"name": null,
"title": null,
... (and so on until we get to the stuff that's unique to this type of user) ...
"favourite_artworks": [
"sunflowers",
"landscapes"
],
"artwork_urls": [
"http://sunflowers.example"
]
}
]
}
User Type B:
{
"success": true,
"num_results": 1,
"user_id": "c1b00cb715",
"results": [{
"user_type": "B",
"group_id": "e7a99e3769",
"name": null,
"title": null,
... (and so on until we get to the stuff that's unique to this type of user) ...
"supported_charities": [
"UN Foundations"
],
"charity_urls": [
"http://www.un.int"
],
}
]
}
What's the correct way to merge together different schemas and properties in OpenAPI? Is this right and Swagger UI just can't handle it?
And how do you mix a schema with properties without having to use allOf?
This suggests it's possible: Swagger Schema: oneOf, anyOf, allOf valid at the same time?
After further investigation, I've determined this is a bug in swagger-ui - https://github.com/swagger-api/swagger-ui/issues/3803 - they simply don't support oneOf (or anyOf) currently.
As far as at least three different linting tools are concerned, a mixture of anyOf, oneOf, and allOf can be used together in the same schema.
Redoc appears to have similar problems - https://github.com/Rebilly/ReDoc/issues/641

Swagger 2.0 semantic error with $ref to path parameter

I am using Swagger Editor to work on a JSON Swagger 2.0 API definition. I have reduced my definition to a minimum example of the problem I am experiencing. The problem occurs when I use a reference object to define a path parameter that is shared between multiple endpoints.
Example endpoints:
/my-api/{id}/some-thing
/my-api/{id}/some-other-thing
Since these id parameters are defined the same way, I abstracted them to the parameters section of the JSON file, and included them with "$ref": "#/parameters/testObjectId".
The Swagger reduced definition shows this:
{
"swagger": "2.0",
"info": {
"title": "Test Service",
"description": "REST API for TestObjects",
"version": "1.0.0"
},
"host": "api.not-a-real-url.com",
"schemes": [
"https"
],
"basePath": "/api/test-objects",
"produces": [
"application/hal+json"
],
"consumes": [
"application/json"
],
"paths": {
"/{id}": {
"get": {
"operationId": "getTestObject",
"summary": "Get a TestObject resource referenced by slug string ID",
"security": [],
"parameters": [
{
"$ref": "#/parameters/testObjectId"
}
],
"responses": {
"200": {
"description": "Success",
"schema": {
"type": "object",
"properties": {}
}
},
"default": {
"description": "Error",
"schema": {
"type": "object",
"properties": {}
}
}
}
}
}
},
"parameters": {
"testObjectId": {
"name": "id",
"in": "path",
"required": true,
"type": "string",
"format": "slug",
"description": "Immutable, unique identifier of a TestObject"
}
},
"definitions": {
}
}
But when this is rendered in Swagger, I get the following error:
Errors
Semantic error at paths./{id}
Declared path parameter "id" needs to be defined as a path parameter at either the path or operation level
The problem is that id is actually defined, only it appears that the check which throws this error is occurring before the $ref is included. The Swagger output looks correct.
Further, I have used this approach for about 6 months (as long as I have used Swagger) and I am just now running into the problem for the first time. Is there something I should be doing differently to prevent this error? Am I misusing Swagger by doing it this way?
Your spec is valid. It was a bug introduced in Swagger Editor v.3.2.2, it was fixed in v.3.2.3 (released on January 6, 2018).

Resources