Sub topic 4
Trying requests in Swagger UI
This chapter assumes you have added the springdoc starter and can open /swagger-ui.html in a running Spring Boot 3 application. It also assumes you know basic HTTP methods and status codes. Here you use the page to send real requests to your API.
What Swagger UI does with the document
Swagger UI is a web page served by your own application. When it loads, it fetches /v3/api-docs and draws one panel for each operation. Pressing Execute makes the browser send an actual HTTP request to the server the page came from.
Because the page and the API share an origin, you normally need no CORS configuration.
Sending a request
Take this controller method from the earlier setup:
@GetMapping("/{id}")
public Book getBook(
@Parameter(description = "Book identifier", example = "42") @PathVariable long id) {
return service.findById(id);
}To call it from the page:
- Expand the Books group, then expand
GET /api/books/{id}. - Click Try it out. The parameter fields become editable.
- The
idfield is pre-filled with42from theexampleattribute. Change it if you like. - Click Execute.
Below the button, Swagger UI shows four things:
- Curl: a command you can paste into a terminal.
- Request URL: the final URL after path and query values are filled in.
- Server response: the status code, body and response headers.
- Responses: the documented status codes, to compare against what you got.
The generated curl command looks like this:
curl -X 'GET' \
'http://localhost:8080/api/books/42' \
-H 'accept: */*'Sending a body
For a POST or PUT, Try it out fills the request body editor with an example built from the schema. If your fields have @Schema(example = ...) values, those appear in the JSON. Edit the JSON, then press Execute. A 400 response here usually means a Bean Validation constraint such as @NotBlank rejected your input, which makes this a quick way to check your constraints.
Common problems
- "Failed to fetch": the server is down, the page was opened through a proxy with a different address, or the browser blocked the call. Look at the browser's network tab.
- Wrong host in the request URL: Swagger UI uses the
serverslist from the document. Behind a reverse proxy this can point at the wrong address, so set the server URL explicitly in theOpenAPIbean. - 401 or 403 on every call: the endpoint is protected and Swagger UI has no token. Documenting a security scheme adds the Authorize button, which a later chapter covers.
Exercise
You press Execute on POST /api/books and receive a 400 response. The body you sent contains "title": "", and title is annotated with @NotBlank. Is this a bug in Swagger UI, and how can you confirm what request was sent?
Show answer
It is not a bug. Validation correctly rejected the empty title. Confirm the request by reading the generated curl command and the Request URL shown under the Execute button, or by checking the browser's network tab.