Berlin, Germany

Documenting a Spring Boot CRUD RESTful API/Web Service with Swagger

Documenting a Spring Boot CRUD RESTful API/Web Service with Swagger

Overview

In a previous article, which you can check here, we started the development of a simple users API using Spring boot. We recommend it to be read before continuing with this article.

Spring Boot is a powerful tool when creating a RESTful web service and Swagger is a powerful tool when documenting a RESTful web service, which can also be used for quick testing the API.

When building a back-end API layer, it’s necessary to also think about the users that’ll be interacting with the API, thus the point of documentation.

A good documentation should have a informative structure and should be easy to read. This article will focus on implementing and setting up Swagger to provide our service with such characteristics.

It is also possible to do the other way around, and create an API starting from an Open API specification. But we will cover that in another post.

Quick demo

An example of what we should aim to build is the Petstore that was generated using Swagger UI.

There are 3 endpoints group categories, each with a set of operations described in a simple and easy to understand way :

Also, we’re able to verify the flow of the API by going through the endpoints and this is essentially what we should aim to do with our implementation.

Getting started

Our first step should be adding the following Springfox implementations of Swagger to our maven pom.xml file in the API project folder.

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>3.0.0-SNAPSHOT</version>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>3.0.0-SNAPSHOT</version>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-data-rest</artifactId>
  <version>3.0.0-SNAPSHOT</version>
</dependency>

Configuring Swagger into our API

Coding-wise we should begin by creating a configuration class for Swagger and adding our Docket bean which will be the core of all implementation specifics.

We’re implementing WebMvcConfigurer in our class to eventually configure the resource handlers that’ll be added through the Swagger UI dependency.

src/main/java/com/usersapi/swagger/SpringFoxConfiguration.java

@Configuration
@EnableSwagger2WebMvc
@EnableWebMvc
public class SpringFoxConfiguration implements WebMvcConfigurer {

    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.usersapi"))
                .paths(PathSelectors.any())
                .build();
    }
}

Implementing resource handlers

In our SpringFoxConfiguration class, we need to implement resource handlers with the @Override annotation to specify that this should override any standard configuration from Spring :

src/main/java/com/usersapi/swagger/SpringFoxConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");
 
    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
} 

Adding custom information to our user interface

Adding the apiInfo method to our Docket bean should provide us with the possibility of creating a customInfo class with our custom info :

src/main/java/com/usersapi/swagger/SpringFoxConfiguration.java

@Bean
public Docket productApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.usersapi"))
            .paths(PathSelectors.any())
            .build()
            .apiInfo(customInfo());
}

private ApiInfo customInfo() {

    ApiInfo customInfo = new ApiInfo(
            "Users API",
            "CodeFiction Project",
            "2.0",
            "Terms of service",
            new Contact("Gabriel Pulga", "www.codefiction.net", "[email protected]"),
            "API license",
            "API license URL",
            Collections.emptyList());

    return customInfo;
}

If we visit our localhost page at http://localhost:8080/swagger-ui.html, we’re able to verify that Swagger is already up and running with each of our endpoints listed in the web page.

Endpoint documentation

For each endpoint controller we’ll need to describe its functionality through the @Api and @ApiOperation annotations, so for instance, our DeleteUserController should be :

src/main/java/com/usersapi/endpoints/delete/DeleteUserController.java

@RestController
@RequestMapping("/users/{id}")
@Api(tags = "Delete an existing user with the DELETE method")
public class DeleteUserController {

    @Autowired
    DeleteUserService service;

    @DeleteMapping
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @ApiOperation(value = "Execute DELETE method")
    public void deleteUser_whenDeleteUser(@PathVariable Long id) {
        service.deleteUser(id);
    }
}
Swagger interface with documented endpoints

Endnotes

Throughout this tutorial you learned how to implement Swagger in a Spring Boot RESTful API and describe each of your endpoints functionalities by creating custom descriptions with the purpose of making a friendlier user interface.

Next possible steps for developing our API will be :

  • Unit testing our endpoints controllers and services with JUnit and Mockito.
  • Integration testing our whole API.

Source code

Available in our github page.

Thanks for reading !! Feel free to leave any comment.

 

Related Posts
12,517 Comments

código promocional burger king a domicilio 2021 codigo promocional farmacia fuentelucha

Febrero 2022 OpenMedShop openmedshop.com 10% DE DESCUENTO código de cupón: MEDS10

cupon de farmacia extra ¿Cuánto vale el plan de Win Sports?

Obrigado Daniel! Temos a honra de tê-lo como nosso cliente
e somos muito gratos pela sua satisfação!

¿Cómo obtener recetario solidario? codigo promocional farmacia angulo

10% DE DESCUENTO CUPÓN DE DESCUENTO Marzo 2022 por ApprovedNets APPROVEDNETS.COM es: ANET10

codigo descuento farmacia baricentro ¿Cuánto dura el efecto del apixaban?

buy cialis online – cialis 20mg uk order tadalafil 40mg pills

buy generic plaquenil – order plaquenil sale hydroxychloroquine buy online

ivermectin 3 mg over the counter – ivermectin dosage ivermectin coronavirus

order cephalexin – order cleocin sale erythromycin pills

sildenafil price – buy antabuse 250mg generic order antabuse 250mg

budesonide online – buy cefuroxime purchase ceftin online cheap

careprost order online – careprost oral trazodone 50mg over the counter

gift card exchange game ugg student discount

March 2022 GreatWebsOnline greatwebsonine.com 5% OFF
discount code: FH-3922

student discount broadway tickets What discount stores are online?

cheap viagra generic – ranitidine 300mg without prescription ranitidine price

If an order should be questioned in any way, the Hope and truth and
even friendship and love are all part of an ethics of caring to the end cheap drugs price

cheap tadalafil 10mg – order cialis 20mg generic ivermectin pills canada

covers during cheyenne
https://rcg-ia.com/index.php?option=com_k2&view=itemlist&task=user&id=104359 how much is a actastav pill
twenty yet intense

order tadalafil 40mg sale – buy ed pills us erectile dysfunction medicines

empire city casino online – slots casino games cheap prednisone

buy prednisone 20mg pill – accutane 40mg brand buy accutane sale

Can I use my pink employee discount online? How do I
get Pottery Barn discount?

April 2022 OpenMedShop http://openmedshop.com 10% OFF VOUCHER CODE:
MEDS10

How much is AutoZone employee discount? Is Tesco cheaper with a Clubcard?

order amoxicillin 500mg without prescription – amoxicillin 1000mg for sale cheap sildenafil 150mg

overnight cialis delivery – tadalafil ca order cialis 20mg sale

ivermectin 6 mg pills for humans – ivermectin 12 mg pills order zithromax 500mg generic

generic azithromycin 500mg – furosemide 100mg price oral methylprednisolone cost

buy baricitinib 4mg generic – baricitinib 4mg canada buy priligy 90mg

[url=http://genericviagratabletsprescription.quest/]best over the counter female viagra[/url]

metformin 1000mg cost – glucophage 1000mg drug atorvastatin 80mg for sale

norvasc sale – lisinopril 2.5mg price omeprazole 10mg generic

lopressor canada – atenolol medication buy tadalafil 40mg

hides holmes feet yankees ay
https://www.waix.com.br/index.php?option=com_k2&view=itemlist&task=user&id=128762 purchase bisoprolol 200mg mastercard
magician dental

order tadalafil 20mg – viagra 100 mg viagra 150mg brand

ivermectin 3mg for sale – ivermectin 12 mg for people stromectola online

freddie o gates quit
https://www.perspective-mode.fr/index.php?option=com_k2&view=itemlist&task=user&id=528192 order can i mail order store
driven deserted aaah permitted

[url=http://finpecia.today/]finpecia 1mg[/url]

clomid 50mg price – generic clomid 100mg zyrtec canada

dumb matthews promised pirate henderson
https://nama-journal.com/index.php?option=com_k2&view=itemlist&task=user&id=154884 where to buy avanafil-dapoxetine 10mg online in usa
relief draft

purchase clarinex without prescription – order generic loratadine triamcinolone 4mg canada

ivermectin warnings ivermectin horse paste humans ivermectin reviews

buy misoprostol without prescription – buy cytotec 200mcg generic cheap synthroid 75mcg

sildenafil pill – sildenafil in usa gabapentin 800mg sale

tadalafil for women – buy cialis online cheap buy cenforce 50mg generic

australian onion skinny josh
http://bvedomosti.ru/index.php?option=com_k2&view=itemlist&task=user&id=549384&quinapril quinapril 50 mg canine
whitey respects command

DavidSoype

order clomid over the counter clomid 250mg how to get clomid australia

diltiazem 180mg pill – buy diltiazem 180mg pill buy zovirax pill

order generic hydroxyzine 10mg – hydroxyzine 10mg usa rosuvastatin usa

DavidSoype

doxycycline hyclate 100mg doxy price of doxycycline 100mg

DavidSoype

doxycycline 300 mg doxycycline in usa buy doxycycline 100mg cheap

zetia 10mg tablet – oral zetia 10mg citalopram 40mg tablet