This blog shows you how to use Swagger Codegen to generate client code for your Spring MVC RESTful API and test it with Swagger UI.
1. Introduction
In this tutorial, you will learn how to use Swagger Codegen to generate client code for your Spring MVC RESTful API and test it with Swagger UI.
Swagger is a popular framework for designing and documenting RESTful APIs. It allows you to define your API using a standard format called OpenAPI Specification (OAS), which can be used to generate interactive documentation, client libraries, server stubs, and more.
Swagger Codegen is a tool that can generate client code for various languages and platforms from an OAS file. It can help you to quickly integrate your API with your applications and reduce the development time and effort.
Swagger UI is a web-based interface that allows you to interact with your API and view its documentation. It can help you to test your API endpoints, parameters, responses, and errors.
By the end of this tutorial, you will be able to:
- Create a simple Spring MVC project with Swagger annotations
- Generate an OAS file from your project using Swagger Maven Plugin
- Generate client code for Java using Swagger Codegen
- Explore the generated code and understand its structure and functionality
- Test your API using Swagger UI and verify its behavior
To follow this tutorial, you will need:
- A basic knowledge of Java and Spring MVC
- An IDE of your choice (such as Eclipse or IntelliJ IDEA)
- Maven installed and configured on your system
- Swagger Codegen CLI downloaded and extracted on your system
Are you ready to get started? Let’s begin with setting up our Spring MVC project with Swagger!
2. Setting up Spring MVC Project with Swagger
In this section, you will learn how to create a simple Spring MVC project with Swagger annotations. You will use Maven to manage the dependencies and build the project. You will also use an IDE of your choice to write the code and run the project.
To create a Spring MVC project with Swagger, you will need to follow these steps:
- Create a new Maven project in your IDE and name it
spring-swagger-demo
. - Add the following dependencies to your
pom.xml
file:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <
3. Generating Client Code with Swagger Codegen
Now that you have a Spring MVC project with Swagger annotations, you can use Swagger Codegen to generate client code for your API. This will allow you to easily integrate your API with your applications and test its functionality.
To generate client code with Swagger Codegen, you will need to follow these steps:
- Generate an OpenAPI Specification (OAS) file from your project using Swagger Maven Plugin. This file will contain the definition of your API and its endpoints, parameters, responses, and errors.
- Choose a target language and platform for your client code. Swagger Codegen supports many languages and platforms, such as Java, Python, Ruby, C#, Android, iOS, and more. You can see the full list of supported languages and platforms here.
- Run Swagger Codegen CLI with the appropriate arguments to generate the client code. You will need to specify the input OAS file, the output directory, and the language option. You can also customize the generated code by using additional options and configuration files. You can see the full documentation of Swagger Codegen CLI here.
For example, if you want to generate Java client code for your API, you can run the following command:
java -jar swagger-codegen-cli.jar generate -i swagger.json -o java-client -l java
This command will generate a Java client code in the java-client
directory using the swagger.json
file as the input.
After you run the command, you will see a message like this:
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/pom.xml [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/README.md [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ApiClient.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ApiException.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/Configuration.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/Authentication.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/HttpBasicAuth.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/ApiKeyAuth.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/OAuth.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/Pair.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ProgressRequestBody.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ProgressResponseBody.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/StringUtil.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/api/DefaultApi.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/model/Greeting.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/test/java/io/swagger/client/api/DefaultApiTest.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/test/java/io/swagger/client/model/GreetingTest.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/.gitignore [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/.travis.yml [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/git_push.sh
This message shows the files that are generated by Swagger Codegen. You can see that there are files for the pom.xml, the README.md, the ApiClient, the ApiException, the Configuration, the Authentication, the Pair, the ProgressRequestBody, the ProgressResponseBody, the StringUtil, the DefaultApi, the Greeting, the DefaultApiTest, the GreetingTest, the .gitignore, the .travis.yml, and the git_push.sh.
These files contain the code and the documentation for your Java client. You can use them to interact with your API and perform various operations, such as creating, updating, deleting, and retrieving data.
In the next section, you will explore the generated code and understand its structure and functionality.
3.1. Installing Swagger Codegen
Before you can generate client code with Swagger Codegen, you need to install it on your system. Swagger Codegen is a Java application that can be run from the command line or as a library. You can download the latest version of Swagger Codegen CLI from here.
To install Swagger Codegen, you will need to follow these steps:
- Download the
swagger-codegen-cli.jar
file from the link above and save it in a folder of your choice. - Open a terminal window and navigate to the folder where you saved the file.
- Run the following command to verify that Swagger Codegen is installed correctly:
java -jar swagger-codegen-cli.jar help
This command will display the usage information and the available commands for Swagger Codegen. You should see something like this:
NAME swagger-codegen-cli - Swagger code generator CLI SYNOPSIS swagger-codegen-cli [-h] [-v] command [command options] COMMANDS config-help Config help for chosen lang generate Generate code with chosen lang help Display help information langs Shows available langs meta MetaGenerator. Generator for creating a new template set and configuration for Codegen. The output will be based on the language you specify, and includes default templates to include. validate Validate specification version Show version information
If you see this output, then you have successfully installed Swagger Codegen on your system. You can now use it to generate client code for your API.
In the next section, you will learn how to run Swagger Codegen and generate client code for Java.
3.2. Running Swagger Codegen
Now that you have installed Swagger Codegen on your system, you can use it to generate client code for your API. This will allow you to easily integrate your API with your applications and test its functionality.
To generate client code with Swagger Codegen, you will need to follow these steps:
- Generate an OpenAPI Specification (OAS) file from your project using Swagger Maven Plugin. This file will contain the definition of your API and its endpoints, parameters, responses, and errors.
- Choose a target language and platform for your client code. Swagger Codegen supports many languages and platforms, such as Java, Python, Ruby, C#, Android, iOS, and more. You can see the full list of supported languages and platforms here.
- Run Swagger Codegen CLI with the appropriate arguments to generate the client code. You will need to specify the input OAS file, the output directory, and the language option. You can also customize the generated code by using additional options and configuration files. You can see the full documentation of Swagger Codegen CLI here.
For example, if you want to generate Java client code for your API, you can run the following command:
java -jar swagger-codegen-cli.jar generate -i swagger.json -o java-client -l java
This command will generate a Java client code in the java-client
directory using the swagger.json
file as the input.
After you run the command, you will see a message like this:
[main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/pom.xml [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/README.md [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ApiClient.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ApiException.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/Configuration.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/Authentication.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/HttpBasicAuth.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/ApiKeyAuth.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/auth/OAuth.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/Pair.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ProgressRequestBody.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/ProgressResponseBody.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/StringUtil.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/api/DefaultApi.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/main/java/io/swagger/client/model/Greeting.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/test/java/io/swagger/client/api/DefaultApiTest.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/src/test/java/io/swagger/client/model/GreetingTest.java [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/.gitignore [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/.travis.yml [main] INFO io.swagger.codegen.AbstractGenerator - writing file /java-client/git_push.sh
This message shows the files that are generated by Swagger Codegen. You can see that there are files for the pom.xml, the README.md, the ApiClient, the ApiException, the Configuration, the Authentication, the Pair, the ProgressRequestBody, the ProgressResponseBody, the StringUtil, the DefaultApi, the Greeting, the DefaultApiTest, the GreetingTest, the .gitignore, the .travis.yml, and the git_push.sh.
These files contain the code and the documentation for your Java client. You can use them to interact with your API and perform various operations, such as creating, updating, deleting, and retrieving data.
In the next section, you will explore the generated code and understand its structure and functionality.
3.3. Exploring the Generated Code
In this section, you will explore the generated code and understand its structure and functionality. You will see how the code is organized into different files and classes, and how they interact with each other. You will also see how the code uses the Swagger annotations and the ApiClient class to communicate with your Spring MVC RESTful API.
The generated code consists of the following files and classes:
pom.xml
: This file contains the Maven configuration and dependencies for your Java client. It also includes theswagger-core
andswagger-annotations
libraries, which are used to parse and validate the OAS file.README.md
: This file contains the documentation and instructions for your Java client. It explains how to build and run the client, how to use theDefaultApi
class, and how to customize the client configuration.ApiClient.java
: This class is the main entry point for your Java client. It handles the HTTP requests and responses, the authentication, the serialization and deserialization, the error handling, and the logging. It also provides methods to set and get the base path, the headers, the timeouts, the user agent, and the debug mode.ApiException.java
: This class is the exception class for your Java client. It wraps the HTTP response and the error message, and provides methods to get the status code, the headers, and the body.Configuration.java
: This class is the configuration class for your Java client. It stores the defaultApiClient
instance and the authentication schemes. It also provides methods to get and set theApiClient
and the authentication.Authentication.java
: This interface is the authentication interface for your Java client. It defines the method to apply the authentication to the HTTP request.HttpBasicAuth.java
: This class is the implementation of theAuthentication
interface for the HTTP basic authentication scheme. It stores the username and password, and encodes them in theAuthorization
header.ApiKeyAuth.java
: This class is the implementation of theAuthentication
interface for the API key authentication scheme. It stores the API key and the location (header or query), and adds them to the HTTP request.OAuth.java
: This class is the implementation of theAuthentication
interface for the OAuth 2.0 authentication scheme. It stores the access token and the token type, and adds them to theAuthorization
header.Pair.java
: This class is a helper class for your Java client. It represents a key-value pair, and provides methods to get and set the key and the value.ProgressRequestBody.java
: This class is a helper class for your Java client. It wraps aRequestBody
and provides a callback interface to monitor the progress of the request.ProgressResponseBody.java
: This class is a helper class for your Java client. It wraps aResponseBody
and provides a callback interface to monitor the progress of the response.StringUtil.java
: This class is a helper class for your Java client. It provides utility methods for string manipulation, such as joining, splitting, encoding, and decoding.DefaultApi.java
: This class is the API class for your Java client. It contains the methods to invoke the endpoints of your Spring MVC RESTful API. It uses theApiClient
class to make the HTTP requests and handle the responses. It also uses theSwagger
annotations to document the parameters, the responses, and the errors.Greeting.java
: This class is the model class for your Java client. It represents the data structure of theGreeting
object, which is used by the/greeting
endpoint of your Spring MVC RESTful API. It contains the fields, the getters, the setters, the constructors, the equals, the hash code, and the to string methods. It also uses theSwagger
annotations to document the properties and the validations.DefaultApiTest.java
: This class is the test class for your Java client. It contains the unit tests for the methods of theDefaultApi
class. It uses theJunit
framework and theMockito
library to create and run the tests.GreetingTest.java
: This class is the test class for your Java client. It contains the unit tests for the methods of theGreeting
class. It uses theJunit
framework and theAssertJ
library to create and run the tests..gitignore
: This file contains the patterns of the files and directories that should be ignored by Git..travis.yml
: This file contains the configuration for the Travis CI service, which is used to automatically build and test your Java client.git_push.sh
: This file contains the script to push your Java client to a Git repository.
You can open these files in your IDE and explore their content. You can also modify them according to your needs and preferences.
In the next section, you will learn how to test your API using Swagger UI and verify its behavior.
4. Testing the RESTful API with Swagger UI
In this section, you will learn how to test your API using Swagger UI and verify its behavior. Swagger UI is a web-based interface that allows you to interact with your API and view its documentation. It can help you to test your API endpoints, parameters, responses, and errors.
To test your API using Swagger UI, you will need to follow these steps:
- Run your Spring MVC project in your IDE or from the command line. This will start the embedded Tomcat server and deploy your application.
- Open a browser window and navigate to
http://localhost:8080/swagger-ui.html
. This will open the Swagger UI page for your API. - Expand the
default-controller
section and click on the/greeting
endpoint. This will show the details of the endpoint, such as the HTTP method, the parameters, the responses, and the examples. - Click on the
Try it out
button and enter a value for thename
parameter. This will enable you to execute the endpoint and see the result. - Click on the
Execute
button and wait for the response. This will send a HTTP request to the endpoint and display the response code, the headers, and the body.
For example, if you enter Bob
as the value for the name
parameter, you will see something like this:
Request URL http://localhost:8080/greeting?name=Bob Response Body { "id": 1, "content": "Hello, Bob!" } Response Code 200 Response Headers { "content-type": "application/json;charset=UTF-8", "date": "Wed, 31 Jan 2024 11:06:04 GMT", "transfer-encoding": "chunked" }
This shows that the endpoint returned a 200 OK response with a JSON body containing the greeting message. You can also see the content type, the date, and the transfer encoding headers.
You can repeat the same steps for different values of the name
parameter and see how the response changes. You can also try to enter invalid values or leave the parameter blank and see how the endpoint handles the errors.
By using Swagger UI, you can test your API and ensure that it works as expected. You can also use it to explore the documentation and the examples of your API.
In the next and final section, you will summarize what you have learned in this tutorial and provide some additional resources for further learning.
5. Conclusion
In this tutorial, you have learned how to use Swagger Codegen to generate client code for your Spring MVC RESTful API and test it with Swagger UI. You have seen how to create a simple Spring MVC project with Swagger annotations, generate an OAS file from your project using Swagger Maven Plugin, generate client code for Java using Swagger Codegen CLI, explore the generated code and understand its structure and functionality, and test your API using Swagger UI and verify its behavior.
By following this tutorial, you have gained the following skills and knowledge:
- How to design and document your RESTful API using Swagger
- How to generate client code for various languages and platforms using Swagger Codegen
- How to customize and configure the generated code using options and configuration files
- How to use the generated code to interact with your API and perform various operations
- How to test your API using Swagger UI and view its documentation and examples
These skills and knowledge can help you to develop and integrate your API with your applications faster and easier, and reduce the development time and effort. They can also help you to ensure the quality and reliability of your API, and improve the user experience and satisfaction.
If you want to learn more about Swagger Codegen, Swagger UI, or Spring MVC, you can check out the following resources:
We hope you enjoyed this tutorial and found it useful. Thank you for reading and happy coding!