dcsimg
September 18, 2019
Hot Topics:

API Development with Swagger

  • February 14, 2019
  • By Robert Gravelle
  • Send Email »
  • More Articles »

Swagger is the most widely used tooling ecosystem for developing APIs with the OpenAPI Specification (OAS). Swagger (now known as the "Open API Initiative") is a specification and framework for describing REST APIs using a common language that's easily read and interpreted by humans and machines alike. JSON provides a machine readable format whereas Swagger-UI allows users to view the API documentation by using a browser. Swagger's tooling includes the Swagger Editor, Swagger CodeGen, Swagger UI, and Swagger Inspector. There are other available frameworks that have gained some popularity, such as RAML, Summation, and so forth, but Swagger has risen to the top of the heap thanks to its many outstanding features and acceptance among the developer community.

The Swagger Petstore
Figure 1: The Swagger Petstore

In this article, we'll use the Swagger CodeGen project to generate a REST client from the Swagger Petstore API example's OpenAPI/Swagger spec file. Then, we'll create a Spring Boot project in which we'll use the generated classes.

Swagger Integration

Swagger can be integrated with REST APIs in two ways:

  • A top-down approach: First API specification and then code generation.
  • A bottom-up approach: First API code and then Swagger integration. This is the typical scenario, which is useful when there is already an existing REST API built in and Swagger documentation needs to be integrated.

In this post, we will follow the less trodden path and go with top-down approach.

Generating the REST Client

Swagger makes the code-gen_cli.jar utility for generation of REST clients in various programming languages and multiple frameworks. You can download it directly from the swagger-codegen-cli GitHub repository.

To see available programming languages, enter the following command:

java -jar swagger-codegen-cli.jar langs.

You also can list all of the Java-related options by typing the following:

java -jar swagger-codegen-cli.jar config-help -l java

Here's the command to generate the client:

java -jar swagger-codegen-cli.jar generate
   -i http://petstore.swagger.io/v2/swagger.json
   --api-package com.robgravelle.petstore.client.api
   --model-package com.robgravelle.petstore.client.model
   --invoker-package com.robgravelle.petstore.client.invoker
   --group-id com.robgravelle
   --artifact-id spring-swagger-codegen-api-client
   --artifact-version 0.0.1-SNAPSHOT
   -l java
   --library resttemplate
   -o spring-swagger-codegen-api-client

There are a lot of command parameters, so here's a brief description of each:

  • The -i argument specifies the source Swagger file URL or path.
  • The names of packages for generated classes are provided using the --api-package, --model-package, and --invoker-package flags.
  • The --group-id, --artifact-id, and --artifact-version flags specify the generated Maven project properties.
  • The programming language of the generated client is provided by using -l.
  • The implementation framework is provided by using the -library flag.
  • The output directory is provided by using -o.

Generating the Spring Boot Project

Now, we're ready to create a new Spring Boot project that utilizes the API.

First, we need to add the dependency of the Generated API Client library to our project's pom.xml file:

<dependency>
   <groupId>com.robgravelle</groupId>
   <artifactId>spring-swagger-codegen-api-client</artifactId>
   <version>0.0.1-SNAPSHOT</version>
</dependency>

To access the generated classes, we need to configure them as beans:

@Configuration
public class PetStoreIntegrationConfig {
 
   @Bean
   public PetApi petApi() {
      return new PetApi(apiClient());
   }

   @Bean
   public ApiClient apiClient() {
      return new ApiClient();
   }
}

The ApiClient class is responsible for configuring authentication, the base path of the API, common headers, as well as for executing all API requests. Here's some code that employs OAuth:

@Bean
public ApiClient apiClient() {
   ApiClient apiClient = new ApiClient();

   OAuth petStoreAuth = (OAuth) apiClient.getAuthentication
      ("petstore_auth");
   petStoreAuth.setAccessToken("special-key");
 
   return apiClient;
}

Next, we need to import the newly created configuration as follows:

@SpringBootApplication
@Import(PetStoreIntegrationConfig.class)
public class PetStoreApplication {
   public static void main(String[] args) throws Exception {
      SpringApplication.run(PetStoreApplication.class, args);
   }
}

Configuring our API classes as beans makes injecting them into our Spring-managed classes a fairly trivial matter:

@Autowired
private PetApi petApi;

public List<Pet> findAvailablePets() {
   return petApi.findPetsByStatus(Arrays.asList("available"));
}

Conclusion

There are other ways to generate a REST client, such as using the Maven Plugin or the Online Generator API. In fact, you'll find that Swagger offers many ways to make developing REST APIs a whole lot easier.







Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Thanks for your registration, follow us on our social networks to keep up-to-date