Swagger UI and Documentation Publishing Tutorial
Swagger UI is an API documentation visualization tool based on the OpenAPI Specification (formerly the Swagger Specification). It can convert API specification documents into interactive API documentation interfaces.
Through Swagger UI, developers and users can:
- View detailed API information
- Test API requests directly on the interface
- View request and response examples
- Understand the functions and parameters of different API endpoints
Advantages of Swagger UI
- VisualizationProvides a clear and intuitive API documentation interface
- InteractivitySupports online API testing without additional tools
- Real-time updatesThe documentation updates automatically after code changes
- StandardizationBased on the OpenAPI Specification, maintaining consistency
- Cross-language supportSuitable for various programming languages and frameworks
Integrate Swagger UI
1. Integrate in a Spring Boot project
Add Dependency
in pom.xml Add the following dependency:
Example
io.springfox
springfox-swagger2
3.0.0
io.springfox
springfox-swagger-ui
3.0.0
Or use SpringDoc OpenAPI:
Example
org.springdoc
springdoc-openapi-ui
1.6.14
Configure Swagger
Example
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
springfox.documentation.builders.ApiInfoBuilder
;
import
springfox.documentation.builders.PathSelectors
;
import
springfox.documentation.builders.RequestHandlerSelectors
;
import
springfox.documentation.service.ApiInfo
;
import
springfox.documentation.service.Contact
;
import
springfox.documentation.spi.DocumentationType
;
import
springfox.documentation.spring.web.plugins.Docket
;
import
springfox.documentation.swagger2.annotations.EnableSwagger2
;
@Configuration
@EnableSwagger2
public
class
SwaggerConfig
{
@Bean
public
Docket api
(
)
{
return
new
Docket
(
DocumentationType.
SWAGGER_2
)
.
select
(
)
.
apis
(
RequestHandlerSelectors.
basePackage
(
"com.example.controller"
)
)
.
paths
(
PathSelectors.
any
(
)
)
.
build
(
)
.
apiInfo
(
apiInfo
(
)
)
;
}
private
ApiInfo apiInfo
(
)
{
return
new
ApiInfoBuilder
(
)
.
title
(
"API interface documentation"
)
.
description
(
"API interface detailed description"
)
.
version
(
"1.0.0"
)
.
contact
(
new
Contact
(
"Development team"
,
"https://example.com"
,
"team@example.com"
)
)
.
build
(
)
;
}
}
For SpringDoc OpenAPI:
Example
import
org.springdoc.core.GroupedOpenApi
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.context.annotation.Configuration
;
import
io.swagger.v3.oas.models.OpenAPI
;
import
io.swagger.v3.oas.models.info.Info
;
import
io.swagger.v3.oas.models.info.Contact
;
@Configuration
public
class
SwaggerConfig
{
@Bean
public
OpenAPI customOpenAPI
(
)
{
return
new
OpenAPI
(
)
.
info
(
new
Info
(
)
.
title
(
"API interface documentation"
)
.
version
(
"1.0.0"
)
.
description
(
"API interface detailed description"
)
.
contact
(
new
Contact
(
)
.
name
(
"Development team"
)
.
(
"team@example.com"
)
.
url
(
"https://example.com"
)
)
)
;
}
@Bean
public
GroupedOpenApi publicApi
(
)
{
return
GroupedOpenApi.
builder
(
)
.
group
(
"public-apis"
)
.
pathsToMatch
(
"/api/**"
)
.
build
(
)
;
}
}
2. Integrate in a Node.js Express project
Install dependencies
npm install swagger-jsdoc swagger-ui-express --save
Configure Swagger
Example
const
express
=
require
(
'express'
)
;
const
swaggerJsDoc
=
require
(
'swagger-jsdoc'
)
;
const
swaggerUi
=
require
(
'swagger-ui-express'
)
;
const
app
=
express
(
)
;
// Swagger configuration
const
swaggerOptions
=
{
definition
:
{
openapi
:
'3.0.0'
,
info
:
{
title
:
'API interface documentation'
,
version
:
'1.0.0'
,
description
:
'API interface detailed description'
,
contact
:
{
name
:
'Development team'
,
:
'team@example.com'
,
url
:
'https://example.com'
}
}
,
servers
:
[
{
url
:
'http://localhost:3000'
,
description
:
'Development server'
}
]
}
,
apis
:
[
'./routes/*.js'
]
// Path to the API route file
}
;
const
swaggerDocs
=
swaggerJsDoc
(
swaggerOptions
)
;
app.
use
(
'/api-docs'
,
swaggerUi.
serve
,
swaggerUi.
setup
(
swaggerDocs
)
)
;
// ... other routes and middleware
app.
listen
(
3000
,
(
)
=>
{
console.
log
(
'Server running at http://localhost:3000'
)
;
console.
log
(
'API documentation is accessible at http://localhost:3000/api-docs'
)
;
}
)
;
3. Use in a Python FastAPI project
FastAPI integrates Swagger UI by default:
Example
from
fastapi
import
FastAPI
app
=
FastAPI
(
title
=
"API interface documentation"
,
description
=
"API interface detailed description"
,
version
=
"1.0.0"
,
contact
=
{
"name"
:
"Development team"
,
"email"
:
"team@example.com"
,
"url"
:
"https://example.com"
,
}
,
)
@
app.
get
(
"/"
)
async
def
root
(
)
:
return
{
"message"
:
"Hello World"
}
Swagger UI is accessible by default at the /docs path; you can view the documentation by visiting http://localhost:8000/docs.
For details, see:FastAPI interactive API documentation
Write API documentation
1. API documentation annotations in a Spring Boot project
Example
import
io.swagger.annotations.*
;
import
org.springframework.web.bind.annotation.*
;
@RestController
@RequestMapping
(
"/api/users"
)
@Api
(
tags
=
"User management"
)
public
class
UserController
{
@ApiOperation
(
value
=
"Get user list"
, notes
=
"Get all user information with pagination"
)
@ApiResponses
(
{
@ApiResponse
(
code
=
200
, message
=
"Success"
)
,
@ApiResponse
(
code
=
400
, message
=
"Request parameter error"
)
,
@ApiResponse
(
code
=
500
, message
=
"Internal server error"
)
}
)
@GetMapping
(
"/"
)
public
Page
<
User
getUsers
(
@ApiParam
(
value
="Page number"
, required
=
true
)
@RequestParam
int
page,
@ApiParam
(
value
=
"Records per page"
, required
=
true
)
@RequestParam
int
size
)
{
// Business logic
return
userService.
getUsers
(
page, size
)
;
}
@ApiOperation
(
value
=
"Get a single user"
, notes
=
"Get user information by ID"
)
@GetMapping
(
"/{id}"
)
public
User getUser
(
@ApiParam
(
value
=
"User ID"
, required
=
true
)
@PathVariable
Long
id
)
{
// Business logic
return
userService.
getUser
(
id
)
;
}
@ApiOperation
(
value
=
"Create user"
, notes
=
"Create a new user"
)
@PostMapping
(
"/"
)
public
User createUser
(
@ApiParam
(
value
=
"User information"
, required
=
true
)
@RequestBody UserDTO userDTO
)
{
// Business logic
return
userService.
createUser
(
userDTO
)
;
}
}
For SpringDoc OpenAPI:
Example
import
io.swagger.v3.oas.annotations.*
;
import
io.swagger.v3.oas.annotations.media.*
;
import
io.swagger.v3.oas.annotations.responses.*
;
import
io.swagger.v3.oas.annotations.tags.Tag
;
import
org.springframework.web.bind.annotation.*
;
@RestController
@RequestMapping
(
"/api/users"
)
@Tag
(
name
=
"User management"
, description
=
"User-related API"
)
public
class
UserController
{
@
Operation
(
summary
=
"Get user list"
,
description
=
"Get all user information with pagination"
)
@ApiResponses
(
value
=
{
@ApiResponse
(
responseCode
=
"200"
, description
=
"Success"
)
,
@ApiResponse
(
responseCode
=
"400"
, description
=
"Request parameter error"
)
,
@ApiResponse
(
responseCode
=
"500"
, description
=
"Internal server error"
)
}
)
@GetMapping
(
"/"
)
public
Page
<
User
getUsers
(
@Parameter
(
description
="Page number"
, required
=
true
)
@RequestParam
int
page,
@Parameter
(
description
=
"Records per page"
, required
=
true
)
@RequestParam
int
size
)
{
// Business logic
return
userService.
getUsers
(
page, size
)
;
}
}
2. API documentation comments in a Node.js Express project
Example
/**
* @swagger
* /api/users:
* get:
* summary: Get user list
* description: Get all user information with pagination
* tags: [User management]
* parameters:
* - in: query
* name: page
* schema:
* type: integer
* required: true
* description: Page number
* - in: query
* name: size
* schema:
* type: integer
* required: true
* description: Records per page
* responses:
* 200:
* description: Success
* content:
* application/json:
* schema:
* type: object
* properties:
* data:
* type: array
* items:
* $ref: '#/components/schemas/User'
* total:
* type: integer
* 400:
* description: Request parameter error
* 500:
* description: Internal server error
*/
router.
get
(
'/users'
,
(
req
,
res
)
=>
{
// Business logic
}
)
;
/**
* @swagger
* components:
* schemas:
* User:
* type: object
* required:
* - name
* - email
* properties:
* id:
* type: integer
* description: User ID
* name:
* type: string
* description: Username
* email:
* type: string
* format: email
* description: User email
*/
3. API documentation in a Python FastAPI project
Example
from
fastapi
import
FastAPI
,
Query
,
Path
from
pydantic
import
BaseModel
from
typing
import
List
,
Optional
app
=
FastAPI
(
title
=
"User management API"
)
class
User
(
BaseModel
)
:
id
:
int
name:
str
:
str
class
Config:
schema_extra
=
{
"example"
:
{
"id"
:
1
,
"name"
:
"Zhang San"
,
"email"
:
"zhangsan@example.com"
}
}
@
app.
get
(
"/api/users/"
,
summary
=
"Get user list"
,
description
=
"Get all user information with pagination"
,
response_model
=
List
[
User
]
,
tags
=
[
"User management"
]
)
async
def
get_users
(
page:
int
=
Query
(
...
,
description
=
"Page number"
,
ge
=
1
)
,
size:
int
=
Query
(
...
,
description
=
"Records per page"
,
ge
=
1
,
le
=
100
)
)
:
Business logic
return
[
{
"id"
:
1
,
"name"
:
"Zhang San"
,
"email"
:
"zhangsan@example.com"
}
,
{
"id"
:
2
,
"name"
:
"Li Si"
,
"email"
:
"lisi@example.com"
}
]
@
app.
get
(
"/api/users/{user_id}"
,
summary
=
"Get a single user"
,
description
=
"Get user information by ID"
,
response_model
=
User
,
tags
=
[
"User management"
]
)
async
def
get_user
(
user_id:
int
=
Path
(
...
,
description
=
"User ID"
,
ge
=
1
)
)
:
Business logic
return
{
"id"
: user_id
,
"name"
:
"Zhang San"
,
"email"
:
"zhangsan@example.com"
}
Customize Swagger UI
1. Spring Boot custom configuration
Example
@Bean
public
Docket api
(
)
{
return
new
Docket
(
DocumentationType.
SWAGGER_2
)
.
select
(
)
.
apis
(
RequestHandlerSelectors.
basePackage
(
"com.example.controller"
)
)
.
paths
(
PathSelectors.
regex
(
"/api/.*"
)
)
.
build
(
)
.
apiInfo
(
apiInfo
(
)
)
.
useDefaultResponseMessages
(
false
)
// Disable default response messages
.
globalResponseMessage
(
RequestMethod.
GET
, globalResponses
(
)
)
// Customize global response messages
.
securitySchemes
(
Arrays
.
asList
(
apiKey
(
)
)
)
// Configure security authentication
.
securityContexts
(
Arrays
.
asList
(
securityContext
(
)
)
)
;
// Configure security context
}
private
List
<
ResponseMessage
globalResponses
(
)
{
return
Arrays.
asList
(
new
ResponseMessageBuilder
(
)
.
code
(
200
)
.
message
(
"Success"
)
.
build
(
)
,
new
ResponseMessageBuilder
(
)
.
code
(
400
)
.
message
(
"Request parameter error"
)
.
build
(
)
,
new
ResponseMessageBuilder
(
)
.
code
(
401
)
.
message
(
"Unauthorized"
)
.
build
(
)
,
new
ResponseMessageBuilder
(
)
.
code
(
403
)
.
message
(
"Forbidden"
)
.
build
(
)
,
new
ResponseMessageBuilder
(
)
.
code
(
500
)
.
message
(
"Internal server error"
)
.
build
(
)
)
;
}
private
ApiKey apiKey
(
)
{
return
new
ApiKey
(
"JWT"
,
"Authorization"
,
"header"
)
;
}
private
SecurityContext securityContext
(
)
{
return
SecurityContext.
builder
(
)
.
securityReferences
(
defaultAuth
(
)
)
.
forPaths
(
PathSelectors.
regex
(
"/api/.*"
)
)
.
build
(
)
;
}
private
List
<
SecurityReference
defaultAuth
(
)
{AuthorizationScope authorizationScope
=
new
AuthorizationScope
(
"global"
,
"accessEverything"
)
;
AuthorizationScope
[
]
authorizationScopes
=
new
AuthorizationScope
[
1
]
;
authorizationScopes
[
0
]
=
authorizationScope
;
return
Arrays
.
asList
(
new
SecurityReference
(
"JWT"
, authorizationScopes
)
)
;
}
2. Express custom configuration
Example
const
options
=
{
customCss
:
'.swagger-ui .topbar { display: none }'
,
// Custom CSS
customSiteTitle
:
"API documentation center"
,
// Page title
customfavIcon
:
"/favicon.png"
,
// Custom icon
swaggerOptions
:
{
persistAuthorization
:
true
,
// Preserve authorization information
docExpansion
:
'none'
,
// Collapse all interfaces by default
tagsSorter
:
'alpha'
,
// Sort tags alphabetically
operationsSorter
:
'alpha'
,
// Sort operations alphabetically
defaultModelsExpandDepth
:
1
,
// Hide models
filter
:
true
,
// Enable filtering
}
}
;
app.
use
(
'/api-docs'
,
swaggerUi.
serve
,
swaggerUi.
setup
(
swaggerDocs
,
options
)
)
;
3. FastAPI custom configuration
Example
from
fastapi
import
FastAPI
from
fastapi.
openapi
.
docs
import
get_swagger_ui_html
from
fastapi.
staticfiles
import
StaticFiles
app
=
FastAPI
(
title
=
"API interface documentation"
,
docs_url
=
None
,
Disable the default Swagger UI
)
app.
mount
(
"/static"
,
StaticFiles
(
directory
=
"static"
)
,
name
=
"static"
)
@
app.
get
(
"/docs"
,
include_in_schema
=
False
)
async
def
custom_swagger_ui_html
(
)
:
return
get_swagger_ui_html
(
openapi_url
=
app.
openapi_url
,
title
=
app.
title
" - API documentation"
,
oauth2_redirect_url
=
app.
swagger_ui_oauth2_redirect_url
,
swagger_js_url
=
"/static/swagger-ui-bundle.js"
,
swagger_css_url
=
"/static/swagger-ui.css"
,
swagger_favicon_url
=
"/static/favicon.png"
,
swagger_ui_parameters
=
{
"docExpansion"
:
"none"
,
"defaultModelsExpandDepth"
: -
1
,
"filter"
:
True
,
}
)
Documentation publishing
1. Internal publishing
For internal team use, you can access it directly through the Swagger UI inside the application:
- Spring Boot:
http://your-app-host:port/swagger-ui/index.html - Express:
http://your-app-host:port/api-docs - FastAPI:
http://your-app-host:port/docs
2. Static document generation
Generate static documentation using Swagger Codegen
# Install Swagger Codegen CLI
wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.35/swagger-codegen-cli-3.0.35.jar -O swagger-codegen-cli.jar
# Generate static HTML documents
java -jar swagger-codegen-cli.jar generate -i http://your-app-host:port/v3/api-docs -l html2 -o ./api-docs
Generate static documentation using Redoc
# Install redoc-cli
npm install -g redoc-cli
# Generate static HTML documents
redoc-cli bundle http://your-app-host:port/v3/api-docs -o ./api-docs/index.html
3. Integrate into the CI/CD pipeline
Add documentation generation and publishing steps to the CI/CD pipeline:
Jenkins pipeline example
Example
pipeline
{
agent any
stages
{
// ... other build and test stages
stage
(
'Generate API Documentation'
)
{
steps
{
sh
'java -jar swagger-codegen-cli.jar generate -i http://your-app-host:port/v3/api-docs -l html2 -o ./api-docs'
}
}
stage
(
'Publish Documentation'
)
{
steps
{
// Publish to the Nginx static file server
sh
'rsync -avz --delete ./api-docs/ user@doc-server:/var/www/api-docs/'
// Or publish to object storage (such as AWS S3)
sh
'aws s3 sync ./api-docs/ s3://your-bucket/api-docs/ --delete'
}
}
}
}
GitHub Actions workflow example
Example
name
:
Generate and Deploy API Docs
on
:
push
:
branches
:
[
main
]
jobs
:
build
and
deploy
:
runs
on
:
ubuntu
latest
steps
:
uses
:
actions
/
checkout
@
v2
name
:
Set up JDK
uses
:
actions
/
setup
java
@
v2
with
:
distribution
:
'adopt'
java
version
:
'11'
name
:
Build application
run
:
.
/
mvnw clean package
name
:
Start application
run
:
|
java
jar target
/
your
app.
jar
&
sleep
30
# Wait for the application to start
name
:
Generate API Documentation
run
:
|
wget
q https
:
//repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.35/swagger-codegen-cli-3.0.35.jar -O swagger-codegen-cli.jar
java
jar swagger
codegen
cli.
jar
generate
i http
:
//localhost:8080/v3/api-docs -l html2 -o ./api-docs
name
:
Deploy to GitHub Pages
uses
:
JamesIves
/
github
pages
deploy
action
@
4.1.5
with
:
branch
:
gh
pages
folder
:
api
docs
4. Use an API documentation management platform
Besides self-hosting, you can also use a professional API documentation management platform:
- Swagger HubProvides API design and documentation hosting services
- PostmanNot only can you test APIs, but you can also publish API documentation
- ReadMe.ioProvides comprehensive API documentation management and a developer portal
- StoplightProvides API design, documentation, and governance tools
5. Deploy Swagger UI with Docker
Example
FROM swaggerapi
/
swagger
ui
:
latest
Set environment variables
ENV SWAGGER_JSON
=/
swagger
/
openapi.
json
ENV BASE_URL
=/
api
docs
Copy the OpenAPI specification file
COPY openapi.
json
/swagger/
Expose the port
EXPOSE
8080
Start Swagger UI
CMD
[
"sh"
,
"/usr/share/nginx/docker-run.sh"
]
Build and run:
docker build -t my-swagger-ui .
docker run -p 8080:8080 my-swagger-ui
Visit: http://localhost:8080/api-docs
Best Practices
1. Documentation standards
- Keep it concise and clear: Descriptions should be concise and to the point
- Group management: Use tags to logically group APIs
- Provide examples: Provide examples for requests and responses
- Standardize error handling: Use a consistent error response format and status codes
- Versioning: Clearly indicate API version information in the documentation
2. Security configuration
- Sensitive information handling: Do not expose sensitive information in the documentation
- Production environment configuration: In production, optionally disable or restrict documentation access
- Authentication mechanism: Configure authentication for documentation access
Example
// Spring Boot: disable Swagger in the production environment
@Bean
public
Docket api
(
)
{
return
new
Docket
(
DocumentationType.
SWAGGER_2
)
.
enable
(
!
environment.
acceptsProfiles
(
Profiles.
of
(
"prod"
)
)
)
// ... other configurations
}
3. Automated testing
Combine documentation and testing to ensure the documentation matches the actual API behavior:
Example
// Spring Boot uses REST Assured and Swagger for testing
@Test
public
void
validateSwaggerDocumentation
(
)
{
// Get Swagger JSON
String
swaggerJson
=
given
(
)
.
when
(
)
.
get
(
"/v3/api-docs"
)
.
then
(
)
.
statusCode
(
200
)
.
extract
(
)
.
asString
(
)
;
// Verify Swagger documentation
OpenAPI openAPI
=
new
OpenAPIParser
(
)
.
readContents
(
swaggerJson,
null
,
null
)
.
getOpenAPI
(
)
;
assertNotNull
(
openAPI
)
;
// Verify whether a specific endpoint is in the documentation
assertNotNull
(
openAPI.
getPaths
(
)
.
get
(
"/api/users"
)
)
;
}
Common Problem Solutions
1. Swagger UI does not display or fails to load
- Check dependency versions: Ensure dependency versions are compatible
- Check configuration classes: Ensure configuration classes are registered correctly
- Check path mappings: Ensure path mappings are correct
- Check CORS settings: If cross-origin access is needed, ensure CORS is configured correctly
2. Incomplete API information
- Check annotations: Ensure all required annotations are added
- Check package scan paths: Ensure the scan path includes all controllers
- Check model classes: Ensure model classes have correct descriptions
3. Production environment security issues
Configure production to disable or protect the documentation:
# application-prod.properties
springdoc.swagger-ui.enabled=false
springdoc.api-docs.enabled=false
Or protect it with basic authentication:
Example
@Configuration
@Profile
(
"prod"
)
public
class
SwaggerSecurityConfig
extends
WebSecurityConfigurerAdapter
{
@Override
protected
void
configure
(
HttpSecurity http
)
throws
Exception
{
http.
requestMatchers
(
)
.
antMatchers
(
"/swagger-ui/**"
,
"/v3/api-docs/**"
)
.
and
(
)
.
authorizeRequests
(
)
.
anyRequest
(
)
.
hasRole
(
"ADMIN"
)
.
and
(
)
.
httpBasic
(
)
;
}
}
---
## 总结
Swagger UI 是一个强大的 API 文档工具,通过正确配置和使用,可以大大提高 API 的可用性和开发效率。本教程介绍了 Swagger UI 的基本概念、集成方法、文档编写、自定义配置、文档发布以及最佳实践,希望对您的 API 文档工作有所帮助。
Remember the following key points:
1. 选择适合项目技术栈的 Swagger 集成方式
2. 精心设计和编写 API 文档注解或注释
3. 根据需要自定义 Swagger UI 界面
4. 选择合适的文档发布方式
5. 遵循最佳实践,确保文档的准确性和安全性
通过合理使用 Swagger UI,您可以为您的 API 提供专业、交互式的文档,让您的 API 更易于理解和使用。