Swagger UI
Ktor allows you to generate and serve Swagger UI for your project based on the existing OpenAPI specification. With Swagger UI, you can visualize and interact with the API resources.
Add dependencies
Serving Swagger UI requires adding the ktor-server-swagger
artifact in the build script:
Configure Swagger UI
To serve Swagger UI, you need to call the swaggerUI method that creates a GET
endpoint with Swagger UI at the path
rendered from the OpenAPI specification placed at swaggerFile
:
This method tries to look up the OpenAPI specification in the application resources. Otherwise, it tries to read the OpenAPI specification from the file system using java.io.File
.
Optionally, you can customize Swagger UI inside the swaggerUI
block. For example, you can use another Swagger UI version or apply a custom style.
You can now run the application and open the /swagger
page to see the available endpoints, and test them.
Configure CORS
To make sure your API works nicely with Swagger UI, you need to set up a policy for Cross-Origin Resource Sharing (CORS). The example below applies the following CORS configuration:
anyHost
enables cross-origin requests from any host;allowHeader
allows theContent-Type
client header used in content negotiation.