Welcome to our guide on Swagger and its role in developing Java-based REST APIs. This guide will explore Swagger, its annotations, and how they help create REST API documentation. So, let’s dive in!
Table of contents
- What is Swagger?
- What is OpenAPI Specification?
- Swagger annotations
- Swagger editor
- How to create REST API documentation using Swagger
- Conclusion
What is Swagger?
Swagger is an API design and documentation software that helps developers efficiently design, build, document, and test RESTful APIs. It can automatically generate interactive API documentation, client SDKs, server stub code, and other necessary components. Developers can easily develop, test, and deploy APIs using Swagger, making the process faster and more streamlined. Swagger is also an open-source project.
Swagger is a set of automation tools that accelerates the development and testing of APIs. It reduces errors and simplifies code management, making it an ideal choice for designing and documenting APIs in web applications and cloud services. Swagger provides valuable assistance in designing and documenting APIs, automatically generating code, and testing APIs.
What is OpenAPI Specification?
The OpenAPI Specification (OAS), previously known as the Swagger Specification, is a standardized format for documenting RESTful APIs. It provides a uniform interface to HTTP APIs independent of programming languages. It describes endpoints, parameters, responses, and authentication methods in YAML or JSON, creating clear and machine-readable documentation.
The OpenAPI Specification (OAS) provides detailed guidance on several key aspects of API design and documentation:
Path templating
Path templating involves using template expressions, enclosed in curly braces ({}), within URL paths to specify replaceable sections using path parameters.
Media types
OAS provides guidelines for defining media types to ensure consistency and connectivity across different resources. It recommends compliance with RFC6838 to facilitate clear communication of data formats between clients and servers.
Some examples of possible media type definitions:
text/plain; charset=utf-8
application/json
application/vnd.github+json
application/vnd.github.v3+json
application/vnd.github.v3.raw+json
application/vnd.github.v3.text+json
application/vnd.github.v3.html+json
application/vnd.github.v3.full+json
application/vnd.github.v3.diff
application/vnd.github.v3.patch
OpenAPI Initiative launched OpenAPI Specification 3.1.0 in February 2021. This version has significant upgrades, such as aligning JSON schema vocabularies, creating new top-level elements for webhook description, identifying API licenses, permitting descriptions to be added alongside schema references, and making the PathItems object optional.
Swagger annotations
Swagger annotations are special Java annotations used to document RESTful APIs using the Swagger framework. These annotations provide metadata about the API endpoints, parameters, responses, and other details, which Swagger uses to generate complete API docs.
Here are some commonly used Swagger annotations:
OpenAPI annotations
| OpenAPI Annotations | Description |
|---|---|
| @OpenAPIDefinition | Marks a class as the root of the OpenAPI definition |
| @Info | Provides metadata about the API such as title, version, and description |
| @Contact | Provides contact information for the API, such as name, email, and URL |
| @License | Specifies licensing information for the API, including the license name and URL |
Operations annotations
| Operations Annotations | Description |
|---|---|
| @Operation | Describes an individual API operation (HTTP method) and its parameters |
| @Parameter | Documents the parameters of an operation, including their type, name, and location |
| @RequestBody | Specifies the request body of an operation, including its schema and media type |
| @ApiResponse | Documents the possible responses of an operation, including response codes and descriptions |
| @Tag | Assigns tags to operations to categorize and organize them in the API documentation |
| @Server | Specifies server information for an API, including URL and description |
| @Callback | Documents callbacks or webhooks supported by the API |
| @Link | Adds links to related resources or operations in the API documentation |
Additional annotations
| Additional Annotations | Description |
|---|---|
| @Schema | Specifies the schema definition for request/response bodies or parameters |
| @Content | Describes the media type and schema for request/response bodies in more detail |
| @SecurityRequirement | Defines security requirements for an operation, specifying the required security schemes |
| @Extension | Allows adding custom extensions to the OpenAPI definition for additional metadata or functionality |
| @Hidden | Marks an operation or parameter as hidden, indicating that it should not be included in the generated API documentation |
Sample annotations in Swagger
Here’s an example explaining the annotations being used:
// Define the OpenAPI definition for the API
@OpenAPIDefinition(info =
// Provide metadata about the API using the @Info annotation
@Info(
// Specify the title of the API
title = "My API",
// Specify the version of the API
version = "0.1",
// Provide a description for the API
description = "This is a description of my API.",
// Define licensing information for the API
license = @License(name = "Apache 2.0", url = "https://automatenow.io/"),
// Define contact information for the API
contact = @Contact(url = "https://automatenow.io/", name = "automateNow", email = "info@automatenow.io")
)
)
public class MyApiDefinition {
// Your API implementation goes here
}Code language: Java (java)
Swagger editor
Swagger Editor is an open-source web-based tool designed to simplify the creation and editing of Swagger specifications. It provides a user-friendly interface for developers to write, visualize, and validate API documentation in YAML or JSON format.
Elements of Swagger editor
File menu
This menu offers options to manage files within the editor. It includes:
Import URL – Allows importing an OpenAPI specification from a remote URL
Import File – Helps in importing an OpenAPI specification from a local file
Save as YAML – Saves the current specification as a YAML file
Convert and Save as JSON – Converts the current YAML specification to JSON format and saves it
Clear Editor – Clears the content of the editor
Edit menu
This section provides functionalities related to editing the OpenAPI specification. It includes:
Convert to YAML – Converts the current JSON specification to YAML format
Load Petstore OAS 3.0 – Loads the Petstore example in OpenAPI 3.0 format
Load Petstore OAS 2.0 – Loads the Petstore example in OpenAPI 2.0 format
Insert menu
Add Path Item – Allows you to add a new path item to the API, representing an endpoint
Add Operation – Adds a new operation (e.g., POST request) to an existing path
Add Info – Inserts or updates the metadata of the API, such as title, version, description, and terms of service
Add External Documentation – Links external documentation to the API definition
Add Tag Declaration – Adds a new tag for categorizing API operations
Add Tags to Operation – Assigns tags to specific operations for better organization
Add Servers – Specifies server URLs for different environments (e.g., development, staging, production)
Add Example Response – Adds example responses to show how the API responds to requests
Generate Server menu
This option automates server-side code generation based on OpenAPI specifications, saving developers time and effort. When you use the Generate Server option, you can select from various programming languages and frameworks to generate server code. These options include ada-server, aspnetcore, finch, go-server, and more. Each option corresponds to a specific programming language or framework, generating server-side code that fits your project’s requirements.
Generate Client menu
Similar to the server generation feature, this option generates client code based on the OpenAPI specification. Similarly, when you choose the Generate Client option, you’ll see a range of choices for generating client-side code in various programming languages and platforms like Ada, C#, android, apex, and others.
How to create REST API documentation using Swagger
Creating REST API documentation with Swagger makes it easier for developers to understand, use, and integrate the API. Here, We will document the endpoint https://reqres.in/api/users/2 (taken from reqres.in), which performs a GET request to retrieve the details of a specific user.
Open your web browser and go to Swagger Editor. To clear the default Pet Store example in Swagger Editor, select all the content on the left side and delete it.
You now have a fresh, blank Swagger Editor to start with.
Provide basic metadata about your API, such as title, description, version, and contact information.
openapi: 3.0.0
info:
title: ReqRes User API
description: Documentation for the ReqRes user endpoint.
version: 1.0.0
contact:
name: API Support
url: https://reqres.in/
email: support@reqres.in
servers:
- url: https://reqres.inCode language: YAML (yaml)
Define the path for the endpoint and specify the HTTP method (GET in this case). Here, we have taken the endpoint as, which returns user details.
paths:
/api/users/2:
get:
summary: Get User by ID
description: Retrieves details of a specific user by their ID.
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
Code language: YAML (yaml)
Define the data model (schema) for the response. This includes the structure of the user data returned by the API.
components:
schemas:
User:
type: object
properties:
data:
type: object
properties:
id:
type: integer
example: 2
email:
type: string
example: janet.weaver@reqres.in
first_name:
type: string
example: Janet
last_name:
type: string
example: Weaver
avatar:
type: string
example: https://reqres.in/img/faces/2-image.jpg
support:
type: object
properties:
url:
type: string
example: https://reqres.in/#support-heading
text:
type: string
example: "For more demo APIs, visit the web page of reqres.in"
Code language: YAML (yaml)
Finally, our API documentation will look like this:
openapi: 3.0.0
info:
title: ReqRes User API
description: Documentation for the ReqRes user endpoint.
version: 1.0.0
contact:
name: API Support
url: https://reqres.in/
email: support@reqres.in
servers:
- url: https://reqres.in
paths:
/api/users/2:
get:
summary: Get User by ID
description: Retrieves details of a specific user by their ID.
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'404':
description: User not found
components:
schemas:
User:
type: object
properties:
data:
type: object
properties:
id:
type: integer
example: 2
email:
type: string
example: janet.weaver@reqres.in
first_name:
type: string
example: Janet
last_name:
type: string
example: Weaver
avatar:
type: string
example: https://reqres.in/img/faces/2-image.jpg
support:
type: object
properties:
url:
type: string
example: https://reqres.in/#support-heading
text:
type: string
example: "For more demo APIs, visit the web page of reqres.in"Code language: PHP (php)
You can use the Insert menu to put your paths and info manually.
Use the options such as Save as YAML and Convert and Save as JSON under the File menu to save your API documentation. The main difference between YAML and JSON is their syntax: YAML emphasizes readability with clear spacing and line breaks, while JSON uses brackets { } and commas, making it more suited for machine parsing.
Once you have completed the documentation, you can see a live preview of your API documentation on the right side of the Swagger Editor. This preview updates in real time as you edit your JSON or YAML files, providing quick feedback on how your API documentation will appear to users.
If you click on Try it out and then click Execute, it will send a request to the specified endpoint (/api/users/2) in this case.
It will then display the response directly within the UI. In this case, the response will contain details of the user with ID 2, including their email, first name, last name, and avatar URL.
You can view both your request and response directly within the Swagger UI too. To view requests and responses locally within the Swagger UI, you need to configure the Swagger UI on your local machine. Once configured, you can interact with your API documentation similarly but in your local environment.
Final thoughts on mastering Swagger with Java
In conclusion, mastering Swagger with Java helps developers to efficiently create, document, and interact with RESTful APIs. By using the OpenAPI Specification, developers can ensure consistency, clarity, and ease of integration across their APIs. Adopting Swagger in Java projects leads to more robust and maintainable API solutions. Happy Testing!
Related articles
- API documentation using Postman
- Top API testing tools
- Rest Assured API testing tutorial
- Swagger-Spring Boot integration
Follow our blog
Be the first to know when we publish new content.
Swagger API documentation tutorial
- How to find an element in Selenium - October 5, 2024
- Resolved: SessionNotCreatedException - October 2, 2024
- Katalon Recorder Automation Overview - September 12, 2024