Sub topic 4
Trying requests in Swagger UI
Swagger UI is a web page that reads your OpenAPI document and turns each operation into a form. You fill in the form, press a button, and the page sends a real HTTP request to your running application. This chapter covers how that works, how to read the results, and the settings and pitfalls that matter once you rely on it.
This chapter assumes you have springdoc-openapi in a Spring Boot 3 project and that /v3/api-docs returns JSON. It also assumes you can read HTTP status codes and JSON bodies. The examples use the Book record and BookController from earlier in the tutorial.
How Swagger UI gets from document to request
Swagger UI is a static JavaScript application that springdoc serves from your own application. When you open it, the browser downloads the OpenAPI JSON from /v3/api-docs and draws the page from that document. Pressing Execute makes the browser call your API directly, using the path, parameters and body described in the same document.
Two consequences follow:
- The request comes from your browser, not from the server. The page needs network access to the API, and any cookies your browser holds for that origin are sent.
- Because the page and the API share an origin, you normally do not hit CORS errors. Problems appear only when the document points at a different host through its
serversentry.
Opening the page
Start the application and open http://localhost:8080/swagger-ui.html. springdoc redirects this to /swagger-ui/index.html, which is the real location. Remember that when you write security rules, because both paths need to be reachable.
The page has these parts:
- The title, version and description from your
OpenAPIbean. - A Servers dropdown.
- An Authorize button, if you have declared a security scheme (a later chapter covers this).
- One collapsible section per tag, such as Books. Operations without a tag are grouped under the controller name, for example
book-controller. - A Schemas section at the bottom, listing every model.
Each operation is a coloured row showing the HTTP method, the path and your @Operation summary.
Executing a request step by step
Take GET /api/books/{id} from BookController.
- Expand the operation. You see the parameter table, with
idmarked as required and showing your description and the example42. - Click Try it out. The fields become editable.
- Enter
42in theidfield. If you setexample = "42"on@Parameter, the field is pre-filled. - Click Execute.
Below the button the page shows:
| Part | What it tells you |
|---|---|
| Curl | The equivalent `curl` command, which you can paste into a terminal. |
| Request URL | The exact URL the browser called, including query string. |
| Server response | The status code, the response body and the response headers. |
| Responses table | The documented responses from `@ApiResponses`, with their schemas. |
Keep the last two apart. The Server response block is what your application actually returned. The Responses table below it is documentation, taken from annotations, and never changes when you execute.
If you request an id that does not exist, the server response shows the 404 with its real body. Comparing that to the documented 404 entry is a quick way to find documentation that has drifted from behaviour.
Sending a request body
For a POST operation, Try it out shows a body editor, pre-filled with an example built from the schema. Add this method to BookController:
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Operation(summary = "Add a book to the catalog")
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Book addBook(@Valid @RequestBody Book book) {
return service.create(book);
}Here BookService.create stands for whatever save method your service already has. Swagger UI builds the example body from the @Schema annotations on the record:
{
"title": "Dune",
"author": "Frank Herbert"
}The id field is missing because it is marked accessMode = READ_ONLY, so springdoc leaves it out of request schemas. Edit the JSON and press Execute. If you clear title, the @NotBlank constraint rejects the request, and you see the 400 response from Spring's validation handling. This lets you test validation rules without writing a client.
The Media type dropdown above the editor lists the content types the operation declares. If a controller consumes more than one, such as JSON and XML, pick the one you want. The Content-Type header follows that choice.
Settings that change the page
springdoc exposes Swagger UI options under springdoc.swagger-ui. These are the ones that help most when testing:
springdoc:
swagger-ui:
path: /swagger-ui.html
try-it-out-enabled: true
display-request-duration: true
persist-authorization: true
operations-sorter: method
tags-sorter: alpha
doc-expansion: none
filter: true| Property | Effect |
|---|---|
| `try-it-out-enabled` | Opens every operation already in edit mode, so you skip the **Try it out** click. |
| `display-request-duration` | Shows how many milliseconds each request took. |
| `persist-authorization` | Keeps entered credentials across page reloads, using browser storage. |
| `operations-sorter` | `alpha` or `method` orders operations inside a tag. Without it, they follow the order in the document. |
| `tags-sorter` | `alpha` sorts the tag sections by name. |
| `doc-expansion` | `none` collapses everything on load. `list` expands tags only. `full` expands all operations. |
| `filter` | Adds a search box that filters tags. |
| `supported-submit-methods` | Lists the methods that get an **Execute** button. |
persist-authorization stores tokens in the browser. That is convenient on a development machine and a risk on a shared one, so enable it only in a development profile.
Making a page read-only
Try it out on a production-like system can modify real data. If you expose the UI to people who should only read the documentation, restrict the buttons:
springdoc:
swagger-ui:
supported-submit-methods:
- getWith this setting, only GET operations offer Execute. This is a convenience and not a security control, since anyone can still send the same requests with curl. Real protection comes from authentication, covered in the chapter on protecting the docs.
Common problems
- Wrong server URL. The Servers dropdown is built from the incoming request. Behind a reverse proxy or under a context path, springdoc may show an internal host or miss the prefix, and every Try it out call fails. Set
server.forward-headers-strategy: frameworkso Spring honours theX-Forwarded-*headers, or declare the server explicitly on theOpenAPIbean. Authorizationas a header parameter. The OpenAPI specification says header parameters namedAuthorization,AcceptorContent-Typeare ignored. Swagger UI follows that rule. To send a token, declare a security scheme and use the Authorize button.- 403 on POST while logged in. If Spring Security uses session cookies with CSRF protection, the browser sends the cookie but not a CSRF token, so Spring Security rejects state-changing calls. The same request works from a token-based client. Test with bearer tokens, or exempt the endpoint in a development profile only.
- 401 on the docs themselves. The UI assets and
/v3/api-docsare ordinary requests. When Spring Security protects the application, you must permit them, as shown in the security chapter. - Stale page. The UI caches the loaded document. After you change annotations and restart, do a hard refresh.
- Real side effects. Execute sends real requests. A
DELETEremoves real rows, so point the UI at a development database.
Checking your work from the terminal
The Curl block lets you reproduce any UI request outside the browser. Copying it is a good habit when a response looks wrong, because it separates problems in the document from problems in the application:
curl -X POST "http://localhost:8080/api/books" \
-H "accept: application/json" \
-H "Content-Type: application/json" \
-d '{"title":"Dune","author":"Frank Herbert"}'If the same call works in the terminal but fails in the UI, look at cookies, CSRF and the selected server. If it fails in both, the bug is in the application.
Exercise
A teammate opens Swagger UI behind a reverse proxy, presses Execute on GET /api/books/42, and gets a network error. The same URL works in the browser address bar. Which two places would you check first, and why?
Show answer
First, the Servers dropdown and the Request URL shown after Execute. Swagger UI builds the URL from the servers entry in the OpenAPI document, and behind a proxy that entry can contain an internal host or miss the path prefix. Second, the proxy and Spring configuration: set server.forward-headers-strategy to framework, make the proxy send X-Forwarded-* headers, or declare the public server URL on the OpenAPI bean. The address bar working shows the API itself is fine and the generated server URL is wrong.
Exercise
Why does the POST example body in Swagger UI omit the id field of the Book record, and how would you check that a blank title is rejected?
Show answer
The id field is annotated with accessMode = Schema.AccessMode.READ_ONLY, so springdoc removes it from request schemas. To check validation, click Try it out on POST /api/books, set title to an empty string, and press Execute. Because of @Valid and @NotBlank, the server response should be a 400.