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).
Related
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"
}
}
}
}
}
}
}
}
}
}
I'm currently configuring a Swagger file to utilize OAuth to retrieve tokens from a site. For brevity, I have removed my schemes and most of my paths as those are fine.
{
"openapi": "3.0.2",
"info": {
"title": "swagger",
"version": "1.0.0",
"description": ""
},
"servers": [
{
"url": "url"
}
],
"paths": {
"/oauth_token.do": {
"post": {
"requestBody": {
"required": true,
"content": {
"application/x-www-form-urlencoded": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"components": {
"securitySchemes": {
"OAuth": {
"type": "oauth2",
"flows": {
"password": {
"tokenUrl": "/oauth_token.do",
"refreshUrl": "/oauth_token.do",
"scopes": {
"useraccount": "utilize user account"
}
}
}
}
}
}
"security": [
{
"OAuth": ["useraccount"]
}
]
}
The endpoint for this API specifies that I should use x-www-form-urlencoded in the header as the Content-Type. When executing this request in Postman, it returns 200 with the desired response.
However, with https://editor.swagger.io I input the same postman request to get the fetch failed error with my Authorize button. To test for this, I created a custom path that specifies that the content should be x-www-form-urlencoded and this also fails.
So, what am I missing in this case? Any help would be appreciated.
I believe the issue was I did not fill out some portions I added on the response for path. Instead I opted to only leave description for the 200 response.
The main error I'm getting now is CORS related which is unrelated to the original question. I'll mark this answered for now.
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.
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"
}
}
Jira has a an /edit endpoint which can be used to add a comment. There is an example in their documentation that suggests this input body to accomplish this:
{
"update": {
"comment": [
{
"add": {
"body": "It is time to finish this task"
}
}
]
}
}
I create the exact same input in my Java code:
private String createEditBody() {
JsonNodeFactory jsonNodeFactory = JsonNodeFactory.instance;
ObjectNode payload = jsonNodeFactory.objectNode();
ObjectNode update = payload.putObject("update");
ArrayNode comments = update.putArray("comment");
ObjectNode add = comments.addObject();
ObjectNode commentBody = add.putObject("add");
commentBody.put("body", "this is a test");
return payload.toString();
}
but when I send this PUT request I get an error saying that the "Operation value must be of type Atlassian Document Format"!
Checking the ADF format it says that "version", "type" and "content" are required for this format. So although their documentation example doesn't seem to be ADF format, I'm trying to guess the format and change it. Here's what I accomplished after modifying my code:
{
"update": {
"comment": [
{
"add": {
"version": 1,
"type": "paragraph",
"content": [
{
"body": "this is a test"
}
]
}
}
]
}
}
the add operation seems to be an ADF but now I get 500 (internal server error). Can you help me find the issue?
Note that the above example from Atlassian documentation is for "Jira Server Platform" but the instance I'm working with is "Jira Cloud Platform" although I think the behaviour should be the same for this endpoint.
after tinkering with the input body, I was able to form the right request body! This will work:
{
"update": {
"comment": [
{
"add": {
"body": {
"version": 1,
"type": "doc",
"content": [
{
"type": "paragraph",
"content": [
{
"type": "text",
"text": "this is a test"
}
]
}
]
}
}
}
]
}
}
The annoying things that I learned along the way:
Jira's documentation is WRONG!! Sending the request in their example will fail!!
after making a few changes, I was able to get 204 from the endpoint while still comment was not being posted! And I guessed that the format is not correct and kept digging! But don't know why Jira returns 204 when it fails!!!