how to separated swagger spec to smaller? - swagger

I tried to separated swagger spec to smaller files because my NodeJS have too many APIs.
If I write all document to 1 file, it will very large.
So I want to break the swagger spec to smaller files.
let see my code above, root file and separated file in the same folder. When I access to apidoc, it show an error:
Resolver error at paths./login.$ref Could not resolve reference: Tried to resolve a relative URL, without having a basePath. path: 'login.json' basePath: 'undefined'
Example
My root swagger spec:
{
"openapi": "3.0.3",
"info": {
"title": "Swagger Petstore - OpenAPI 3.0",
"description": "This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about\nSwagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\n\n_If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_\n\nSome useful links:\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam#swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0.11"
},
"paths": {
"/login": {
"$ref": "login.json#/paths/~1login"
}
}
}
My separated spec:
{
"openapi": "3.0.3",
"info": {
"title": "Swagger Petstore - OpenAPI 3.0",
"description": "This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about\nSwagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\n\n_If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_\n\nSome useful links:\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam#swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0.11"
},
"paths": {
"/login": {
"post": {
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"email": {
"type": "string"
},
"password": {
"type": "string"
}
}
}
}
}
}
}
}
}
}

Related

Springdoc sends Multipart file as application/x-www-form-urlencoded and not multipart/form-data

I am using the latest version of openapi-ui 1.6.7 and I can't make a file upload endpoint work.
This is my configuration of the parameter :
#PostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
#Operation(
summary = "Create a new FileResource",
requestBody = #RequestBody(description = "File to upload")
)
public ResponseEntity<FileResourceIdPublicApiDto> create(
#Parameter(
description = "File to upload",
required = true
)
#RequestPart
MultipartFile file
When I use the "Try out" button in the generated swagger UI, I get a 415 Unsupported Media Type error.
The request headers has content-type : application/x-www-form-urlencoded
I think this is where the error comes from. The generated json from OpenApi looks like this :
{
"operationId": "create_4",
"parameters": [
...
],
"requestBody": {
"content": {
"multipart/form-data": {
"schema": {
"required": [
"file"
],
"type": "object",
"properties": {
"file": {
"type": "string",
"format": "binary",
"description": "File to upload"
}
}
}
}
},
"description": "File to upload"
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/FileResourceId"
}
}
},
"description": "OK"
}
},
"summary": "Create a new FileResource",
"tags": [
"File Resource"
]
}
What am I missing to send a correct request with form-data content-type ?
For me replacing RequestPart to RequestParam did the job! btw I was using openapi-ui 1.6.4.
It’s a combination of two things:
Defining “consumes = multipart” and using RequestParam instead of RequestPart.
This wasn’t required when using springfox Swagger 2.0.
It’s really irritating that there is no good migration guide written for 2.0 -> 3.0.

Unable to add Teams/SharePoint file attachment in a task to ' Tasks by Planner and To Do '

I have a fully built API, that creates tasks into MS Teams "Tasks by Planner and To Do".
MS actual graph API used POST https://graph.microsoft.com/v1.0/planner/tasks
Sample API:
{
"routeId": "7fcxxxxx-xxxx-xxxx-xxxx-5d35838xxxxx",
"userId": "77cxxxxx-xxxx-xxxx-xxxx-5f09858xxxxx",
"tenantId": "dcdxxxxx-xxxx-xxxx-xxxx-31002a1xxxxx",
"title": "Task: Add you task title",
"hospitalAssignment": null,
"percentComplete": 0,
"createdTimestamp": "2021-04-20T01:51:49Z",
"startDateTimestamp": "2021-04-20T18:10:15Z",
"dueDate": "2021-11-20T11:47:33.000Z",
"Notes": "Add some useful notes here",
"checklistItems": [
{
"title": "itema"
},
{
"title": "itemb"
}
],
"attachments": [
{
"url": "https://www.google.com",
"alias": "link"
},
{
"url": "https://teams.microsoft.com/file/....",
"alias": "Test Document 1"
},
{
"url": "https://random.sharepoint.com/sites/...",
"alias": "Test Document 2"
},
],
"comments": "null,",
"priority": null
}
Hitting the above API creates a task in the planner as seen below
So, here is an issue - when I try to click on link it took me to the browser and opens up google which is fine. Now, when I click on Test Document 1 or Test Document 2 it throws an unknown error and Sorry, something went wrong respectively.
After that, I created the task manually and adding the attachments from Add Attachment and paste the links to the file there, then click the files works and opens up the documents.
Assuming you are referring to adding / updating the Planner Task Details for a PlannerTask;
there is a sample provided of adding (PATCH) a pptx file using a 'teams path' as you referred to it.
Note that the path must be (url)encoded.
Tasks - plannerTaskDetail < references
https://learn.microsoft.com/en-us/graph/api/resources/plannerexternalreferences?view=graph-rest-1.0
{
"https%3A//contoso%2Esharepoint%2Ecom/teams/agile/documents/AnnualReport%2Epptx":
{
"#odata.type": "microsoft.graph.externalReference", // required in PATCH requests to edit the references on a task
"alias": "Agile Team Annual Report",
"lastModifiedBy": {
"user": {
"id": "ebf3b108-5234-4e22-b93d-656d7dae5874"
}
},
"lastModifiedDateTime": "2015-09-21T17:45:12.039Z",
"previewPriority": "0009005756397228702",
"type": "PowerPoint"
}
}

Swagger UI/Swashbuckle response description with caret not rendering correctly

I am using Swashbuckle with Swagger UI in a .Net project. I am using the following attribute on a controller.
[SwaggerResponse(HttpStatusCode.OK, "IEnumerable<EmployeeModel>", typeof(IEnumerable<EmployeeModel>))]
The generated JSON doc produces this:
"responses": {
"200": {
"description": "IEnumerable<EmployeeModel>",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/ResourceModels.EmployeeModel"
}
}
},
"400": {
"description": "BadRequest"
}
}
Swagger UI however only displays IEnumerable and drops the <EmployeeModel>. I am sure the carets are the culprit. Is there a workaround for this?
According to Swagger:
That's actually a bug in the description. That field is gfm, meaning anything in <> will be treated as html, so if you want those characters to appear you need to escape them.

Making AutoRest map classes to sub-objects in the response

I'm trying to write a client to a large non Swagger-documented API and thought that writing the swagger.json
for it and using AutoRest would be a good way to accomplish that. The case is that this API wraps each operation's
response data into a larger object with control information, like this:
{
"resp_code": "SUCCESS",
"caller_ref": "2016111116233156169531",
"server_ref": "2016111116233189512798",
"data": {
"id": "idstring",
"name": "nameString",
"address": "addressString",
...
}
}
Where "data" in this case would be a "Client" definition for us. Is there a way to define the 200 OK response
schema and the definitions in the swagger.json file so that AutoRest would map this "data" to a Client class?
In fact the answer is quite trivial, all I had to do is to write the "responses" object of the swagger file like this:
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "object",
"properties": {
"data": {
"$ref": "#/definitions/Client"
}
}
}
}
}
Besides creating the Client definition. AutoRest generates code that retrieves the "data" object, giving access to the Client within.

How to import Swagger APIs into Postman?

Recently I wrote restful APIs with SpringMvc and swagger-ui(v2). I noticed the Import function in Postman:
So my question is how to create the file which Postman needed?
I am not familiar with Swagger.
I work on PHP and have used Swagger 2.0 to document the APIs.
The Swagger Document is created on the fly (at least that is what I use in PHP). The document is generated in the JSON format.
Sample document
{
"swagger": "2.0",
"info": {
"title": "Company Admin Panel",
"description": "Converting the Magento code into core PHP and RESTful APIs for increasing the performance of the website.",
"contact": {
"email": "jaydeep1012#gmail.com"
},
"version": "1.0.0"
},
"host": "localhost/cv_admin/api",
"schemes": [
"http"
],
"paths": {
"/getCustomerByEmail.php": {
"post": {
"summary": "List the details of customer by the email.",
"consumes": [
"string",
"application/json",
"application/x-www-form-urlencoded"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "email",
"in": "body",
"description": "Customer email to ge the data",
"required": true,
"schema": {
"properties": {
"id": {
"properties": {
"abc": {
"properties": {
"inner_abc": {
"type": "number",
"default": 1,
"example": 123
}
},
"type": "object"
},
"xyz": {
"type": "string",
"default": "xyz default value",
"example": "xyz example value"
}
},
"type": "object"
}
}
}
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "Email required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getCustomerById.php": {
"get": {
"summary": "List the details of customer by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Customer ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the customer"
},
"400": {
"description": "ID required"
},
"404": {
"description": "Customer does not exist"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
},
"/getShipmentById.php": {
"get": {
"summary": "List the details of shipment by the ID",
"parameters": [
{
"name": "id",
"in": "query",
"description": "Shipment ID to get the data",
"required": true,
"type": "integer"
}
],
"responses": {
"200": {
"description": "Details of the shipment"
},
"404": {
"description": "Shipment does not exist"
},
"400": {
"description": "ID required"
},
"default": {
"description": "an \"unexpected\" error"
}
}
}
}
},
"definitions": {
}
}
This can be imported into Postman as follow.
Click on the 'Import' button in the top left corner of Postman UI.
You will see multiple options to import the API doc. Click on the 'Paste Raw Text'.
Paste the JSON format in the text area and click import.
You will see all your APIs as 'Postman Collection' and can use it from the Postman.
You can also use 'Import From Link'. Here paste the URL which generates the JSON format of the APIs from the Swagger or any other API Document tool.
This is my Document (JSON) generation file. It's in PHP. I have no idea of JAVA along with Swagger.
<?php
require("vendor/autoload.php");
$swagger = \Swagger\scan('path_of_the_directory_to_scan');
header('Content-Type: application/json');
echo $swagger;
With .Net Core it is now very easy:
You go and find JSON URL on your swagger page:
Click that link and copy the URL
Now go to Postman and click Import:
Select what you need and you end up with a nice collection of endpoints:
The accepted answer is correct but I will rewrite complete steps for java.
I am currently using Swagger V2 with Spring Boot 2 and it's straightforward 3 step process.
Step 1: Add required dependencies in pom.xml file. The second dependency is optional use it only if you need Swagger UI.
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Step 2: Add configuration class
#Configuration
#EnableSwagger2
public class SwaggerConfig {
public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "hello#email.com");
public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());
#Bean
public Docket api() {
Set<String> producesAndConsumes = new HashSet<>();
producesAndConsumes.add("application/json");
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT_API_INFO)
.produces(producesAndConsumes)
.consumes(producesAndConsumes);
}
}
Step 3: Setup complete and now you need to document APIs in controllers
#ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
#ApiResponses(value = { #ApiResponse(code = 200, message = "Success"),
#ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
#GetMapping(path = "/articles/users/{userId}")
public List<Article> getArticlesByUser() {
// Do your code
}
Usage:
You can access your Documentation from http://localhost:8080/v2/api-docs just copy it and paste in Postman to import collection.
Optional Swagger UI: You can also use standalone UI without any other rest client via http://localhost:8080/swagger-ui.html and it's pretty good, you can host your documentation without any hassle.
Recommend you to read this answer
https://stackoverflow.com/a/51072071/4712855
Refer to the https://stackoverflow.com/posts/39072519 answer, and then partially delete the returned content. Finally, it is found that swagger lacks some configuration and postmat cannot be imported.
You need to add the following configuration in swagger
#Bean
public Docket api(SwaggerProperties swaggerProperties) {
swaggerProperties.setTitle("my-project");
swaggerProperties.setDescription("my project");
swaggerProperties.setVersion("v1");
swaggerProperties.getContact().setUrl("http");
//I overlooked other configurations. Note that my swagger configuration lacks these.
}
In short, the attributes in the ApiInfoBuilder class are assigned values as much as possible
spring-boot version:2.3.10.RELEASE
springfox-swagger version: 2.9.2
You can do that: Postman -> Import -> Link -> {root_url}/v2/api-docs
This is what worked for me from the Swagger editor interface:
Method 1
Copy the YAML file contents into the Raw Text area:
Method 2 (more steps)
Step 1: Export the file as JSON
Step 2: Import the JSON file with Postman "Import"
Click on the orange button ("choose files")
Browse to the Swagger doc (swagger.yaml)
After selecting the file, a new collection gets created in POSTMAN. It will contain folders based on your endpoints.
You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).

Resources