Testing your API from Swagger UI
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A tester must check that create answers 201 and that a duplicate SKU gives 409. Writing a client for each check is slow, and nobody notices when the docs stop matching the API.
Try it out: filling parameters and editing the request body
Try it out is the button on an open operation in Swagger UI that turns its parameters and request body into input boxes. Execute then sends a real request to the server in the Servers box.
Open POST /api/v1/products in Swagger UI, press Try it out, then Execute. Here is the page and what it sends.
Example 1 · Try it out on POST /api/v1/products
Runs in: the shoplite-api Spring Boot project
Swagger UI (http://localhost:8080/swagger-ui.html), Products, POST /api/v1/products1. Click the row to open it, then click "Try it out" (it turns into "Cancel").2. The Request body box becomes editable and holds the Example Value:{ "sku": "ACC-KB100", "name": "Zebronics Wireless Keyboard", "categoryId": 4, "price": 999, "stock": 0, "isActive": true}3. Change "stock" to 30, then click the blue "Execute" button.Server response
Code Details
201 Response body
{
"id": 16,
"sku": "ACC-KB100",
"name": "Zebronics Wireless Keyboard",
"categoryId": 4,
"categoryName": "Accessories",
"price": 999,
"stock": 30,
"isActive": true
}
Response headers
connection: keep-alive
content-type: application/json
date: Fri,16 Oct 2026 05:21:36 GMT
keep-alive: timeout=60
location: http://localhost:8080/api/v1/products/16
transfer-encoding: chunked
(Press Execute a second time with the same body:)
409 Error: response status is 409
{
"type": "https://shoplite.example/problems/already-exists",
"title": "Resource already exists",
"status": 409,
"detail": "A product with SKU ACC-KB100 already exists.",
"instance": "/api/v1/products"
}What this code does
- The first Execute creates product 16: code 201, the body with
categoryNamefilled in by the server, and alocationheader with the new product's URL. - The second Execute with the same SKU is refused with 409 already-exists, exactly as the
AlreadyExistsresponse in the docs says. - The product really exists now; restart ShopLite (it keeps data in memory for now) or delete it to start clean.
The boxes start with the examples and defaults from the spec, which is why the @Schema examples matter. Path parameters marked * are required: Execute refuses to send without them. Query parameters you leave empty are not sent at all, and boolean ones get a true/false drop-down. Cancel turns the boxes back into plain docs.
The body box holds JSON text. Edit it like any text, but keep it valid JSON: a missing comma or quote is sent as it is, and ShopLite answers 400 malformed-request. Reset puts the example back.
Reading the response code, headers and body
The Server response block in Swagger UI shows the real result of Execute: the status code, the response body and the response headers. The Responses block under it still shows what the docs promise.
Here is a 404, read in Swagger UI after asking for category 99.
Example 2 · Reading a 404 in Swagger UI
Runs in: the shoplite-api Spring Boot project
Products, GET /api/v1/products/{id}, Try it outid * (path): 99 (the box first shows the example, 1)ExecuteRequest URL
http://localhost:8080/api/v1/products/99
Server response
Code Details
404 Error: response status is 404
Response body [Download]
{
"type": "https://shoplite.example/problems/not-found",
"title": "Resource not found",
"status": 404,
"detail": "Product 99 was not found.",
"instance": "/api/v1/products/99"
}
Response headers
connection: keep-alive
content-type: application/problem+json
date: Fri,16 Oct 2026 05:23:10 GMT
keep-alive: timeout=60
transfer-encoding: chunked
Responses (the documented ones, below the live result)
Code Description
200 The product
404 No resource has this idWhat this code does
- The live response is 404 with
content-type: application/problem+json, the same code and type the docs list under Responses. - The body's fields come in the server's order (
detailfirst). JSON clients read fields by name, so the order does not matter. - If the live code were missing from the Responses list, the docs would be wrong, and that is the bug to report.
Comparing the two blocks is the quickest docs review there is. For an error, the code column says "Error: response status is 404" in red, and the body is the Problem Details JSON. Check that its type, status and detail match the error the docs list for that code.
Header names are shown in lower case (location, content-type), which is normal: HTTP header names ignore case. Swagger UI also shows numbers the browser way: 999.00 from the server is displayed as 999. The bytes on the wire still have two decimals; curl shows that, as the next section does.
The curl command Swagger UI generates
The Curl box in Swagger UI shows the request you just executed as a curl command, plus the full Request URL. Copy it to repeat the call in a terminal or paste it into a bug report.
Here is the curl command Swagger UI generated, run in a terminal with -i to show the headers.
Example 3 · The generated curl command, run in a terminal
Runs in: the shoplite-api Spring Boot project
# Swagger UI, GET /api/v1/products, Try it out: set categoryId 2, size 2, sort price,desc;# clear q, minPrice and maxPrice (Try it out pre-fills their examples), then Execute.# The Curl box above the response shows this command, with a copy button:curl -X 'GET' \ 'http://localhost:8080/api/v1/products?categoryId=2&inStock=false&includeInactive=false&page=0&size=2&sort=price%2Cdesc' \ -H 'accept: application/json'# Paste it into Git Bash or the macOS Terminal; add -i to see the status line and headers.$ curl -i -X 'GET' 'http://localhost:8080/api/v1/products?categoryId=2&inStock=false&includeInactive=false&page=0&size=2&sort=price%2Cdesc' -H 'accept: application/json'
HTTP/1.1 200
Content-Type: application/json
Content-Length: 336
Date: Fri, 16 Oct 2026 05:31:22 GMT
{"content":[{"id":3,"sku":"MOB-IP15","name":"iPhone 15 128GB","categoryId":2,"categoryName":"Mobiles","price":69900.00,"stock":8,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":0,"size":2,"totalElements":3,"totalPages":2}What this code does
- The command is exactly what Swagger UI sent, including
inStock=falseandincludeInactive=falsefrom the drop-down defaults andsort=price%2Cdesc. - With
-ithe terminal shows the status line andContent-Length: 336; the prices keep their decimals:69900.00. - The result matches the ShopLite contract's worked example: page 0 of Mobiles, most expensive first, 3 in total.
The command is written for a Unix-style shell, with single quotes and a \ at each line end. It runs as it is in Git Bash and the macOS Terminal; in Windows PowerShell, use curl.exe and join the lines, because Command Prompt does not accept the single quotes.
Notice what Swagger UI sends: accept: application/json, every query parameter that has a value (also the false defaults), and %2C in place of the comma in price,desc, which is URL encoding. The server reads it as price,desc.
Exporting the spec and importing it into Postman as a collection
A Postman collection is a saved folder of ready requests. Importing an OpenAPI file creates one request per operation, with example bodies and parameters filled in, and a baseUrl variable taken from servers.
Save the spec from the running app with curl, then import that file into Postman.
Example 4 · Export the spec and import it into Postman
Runs in: the shoplite-api Spring Boot project
# with ShopLite running (dev profile)curl -o shoplite-openapi.json http://localhost:8080/v3/api-docscurl -o shoplite-openapi.yaml http://localhost:8080/v3/api-docs.yaml$ curl -s -o shoplite-openapi.json -w "%{http_code} %{size_download} bytes\n" http://localhost:8080/v3/api-docs
200 15440 bytes
Postman (desktop app):
1. Click Import (top left of the sidebar), then drop shoplite-openapi.json on the dialog
or click "files" and choose it.
2. Postman detects an OpenAPI 3.1 file. Choose to import it as a Postman Collection.
3. The new collection is named "ShopLite API" (from info.title). It has one folder per path
segment or per tag (an import setting), and one request per operation, named from its
summary: "Create a product", "Get one product", ...
4. The collection's variable baseUrl = http://localhost:8080 (from servers), and every request
URL starts with {{baseUrl}}. Bodies and query parameters are filled from the examples.
Postman's screens move between versions; if a label differs, look for Import and "Postman Collection".What this code does
- The JSON file is the full spec (15440 bytes for the catalogue endpoints); the YAML file holds the same document.
- Postman builds the collection from
info.title, the operations' summaries, the examples andserversas{{baseUrl}}. - Run "Get one product", then change
baseUrlto another server and run it again: one variable moves the whole collection.
Exporting the spec means saving /v3/api-docs to a file. The file is what you hand to other teams, and it works even when your server is off. In Postman each request is named from its summary, and changing baseUrl once points every request at another server.
Export from the running app, as the curl command does. The spec's servers URL is the address you asked, so http://localhost:8080 is right for local testing. A spec saved from a test has http://localhost with no port, and the import gets the wrong baseUrl.
docs/shoplite-openapi.json) so other developers can import it without running ShopLite. Export it again whenever the API changes.Keeping the docs true: checking them in a test
A docs test is an automated test that reads /v3/api-docs and checks it against the API contract: the title, version, listed paths and the exact status codes of each endpoint.
This Spring Boot test checks ShopLite's spec. A second example shows what happens when a status code goes missing.
Example 5 · src/test/java/com/shoplite/ApiDocsTest.java
Runs in: the shoplite-api Spring Boot project
// src/test/java/com/shoplite/ApiDocsTest.javapackage com.shoplite;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;import org.springframework.test.web.servlet.assertj.MockMvcTester;
/** Keeps the published API docs true to the API contract (API-DESIGN.md). */@SpringBootTest@AutoConfigureMockMvcclass ApiDocsTest {
@Autowired private MockMvcTester mvc;
@Test void specHasShopLiteInfoAndOnlyV1Paths() { assertThat(mvc.get().uri("/v3/api-docs")) .hasStatusOk() .bodyJson() .hasPathSatisfying("$.info.title", title -> assertThat(title).asString().isEqualTo("ShopLite API")) .hasPathSatisfying("$.info.version", version -> assertThat(version).asString().isEqualTo("v1")) .extractingPath("$.paths").asMap() .containsOnlyKeys("/api/v1/categories", "/api/v1/categories/{id}", "/api/v1/products", "/api/v1/products/{id}"); }
@Test void createProductDocumentsEveryStatusOfTheContract() { assertThat(mvc.get().uri("/v3/api-docs")) .bodyJson() .extractingPath("$.paths['/api/v1/products'].post.responses").asMap() .containsOnlyKeys("201", "400", "409", "422"); }
@Test void deleteEndpointsDocument204NotA200() { assertThat(mvc.get().uri("/v3/api-docs")) .bodyJson() .extractingPath("$.paths['/api/v1/categories/{id}'].delete.responses").asMap() .containsOnlyKeys("204", "404", "409"); }}$ mvn test -Dtest=ApiDocsTest ... [INFO] Running com.shoplite.ApiDocsTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 28.48 s -- in com.shoplite.ApiDocsTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
What this code does
- The first test checks the cover page and that the documented paths are exactly the four
/api/v1catalogue paths. - The other two compare the documented status codes of two endpoints with the contract table: 201, 400, 409, 422 for create; 204, 404, 409 for delete.
- It starts the whole app, so it takes some seconds; add a check for each endpoint you document.
Example 6 · The docs test catches a missing 204
Runs in: the shoplite-api Spring Boot project
// CategoryController.java: someone deletes the 204 line while tidying up@Operation(operationId = "deleteCategory", summary = "Delete a category", description = "Only a category with no products and no sub-categories can be deleted.")@ApiResponse(responseCode = "404", ref = "NotFound")@ApiResponse(responseCode = "409", ref = "InUse")@DeleteMapping("/{id}")ResponseEntity<Void> delete(@Parameter(description = "Category id", example = "7") @PathVariable Long id) { service.delete(id); return ResponseEntity.noContent().build();}$ mvn test -Dtest=ApiDocsTest
...
[ERROR] com.shoplite.ApiDocsTest.deleteEndpointsDocument204NotA200 -- Time elapsed: 0.070 s <<< FAILURE!
java.lang.AssertionError:
Expecting actual:
{"404"={"$ref"="#/components/responses/NotFound"}, "409"={"$ref"="#/components/responses/InUse"}}
to contain only following keys:
["204", "404", "409"]
but could not find the following keys:
["204"]
at com.shoplite.ApiDocsTest.deleteEndpointsDocument204NotA200(ApiDocsTest.java:44)
...
[ERROR] Tests run: 3, Failures: 1, Errors: 0, Skipped: 0
[INFO] BUILD FAILUREWhat this code does
- Without the 204 line the spec has only 404 and 409 for the delete: springdoc adds no success response when other
@ApiResponselines exist. - The API still answers 204, so nothing else would notice. The test fails with the exact missing key and line 44.
- Put the
@ApiResponse(responseCode = "204", ...)line back and the test passes again.
Docs annotations never change behaviour, so wrong docs compile and run without any warning. The first person to notice is the frontend developer, days later. A docs test runs with mvn test, so a pull request that breaks the docs fails like one that breaks the code, and the failure names the endpoint and the missing status.
@SpringBootTest starts the whole app (springdoc is not part of a @WebMvcTest slice), and @AutoConfigureMockMvc with MockMvcTester sends the request without a real port. extractingPath("$.paths[...]...responses").asMap().containsOnlyKeys(...) checks the exact set of status codes: a missing 204 and an extra 200 both fail.
Next step
Check your understanding
12 quick questions