Facebook Twitter Instagram
    Sunday, July 3
    Trending
    • Ethereum average gas fee falls down to $1.57, the lowest since 2020
    • Traveling to Every Country in the World
    • Language Hacking to Become Fluent in 3 Months
    • China’s top diplomat makes first trip to Myanmar since coup | Politics News
    • Travis Barker & Kourtney Kardashian Speak Out After He Was Hospitalized With ‘Life Threatening Pancreatitis’
    • Will Westworld Finish Where it Began?
    • Lights, Camera, Action
    • AIFF sack Women’s U-17 assistant coach Alex Ambrose due to sexual misconduct
    Facebook Twitter Instagram Pinterest VKontakte
    Swave Digest
    • Home
    • World News
    • Technology
      • Smartphones
      • Computers
      • Programming
      • Automobiles
    • Entertainment
      • Music
      • Anime
      • Movies
    • Sports
      • Football
      • Basketball
      • Tennis
    • Business
      • Crypto
      • Stocks
      • NFT
    • Lifestyle
      • Fashion
      • Health
      • Travel
    • Shop
    Swave Digest
    Home»Technology»Programming»Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022
    Programming

    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022

    Swave DigestBy Swave DigestJune 17, 2022No Comments5 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Table of Contents

    • Documentations made easy
    • Documentation with Annotations
    • Securing Swagger
    • Generate Client Libraries
    • Automated Testing

    Documentations made easy

    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022 4415 829434Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022 4415
    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022

    APIs are one of the key players in the technology world whether they are used in a simple mobile application in integrating complex enterprise systems. Any application can become a platform by enabling methods to enhance and add services to existing products using APIs.

    Having good documentation for these APIs is critical to their success. API documentation is technical content that includes instructions on using and integrating the APIs. Think of it as a reference manual with all of the information you need to work with the API, like the request and response format, and how to start working with them.

    You can always have your format of documentation for your APIs, but having a standard or a common format will make it more readable. Using good practices like Spec-driven development (SDD) also can help in keeping documentation effective. There are several specifications to get started with documenting, such as RAML (RESTful API Modeling Language), OpenAPI (formerly Swagger), and API Blueprint, but in this article, we will focus on OpenAPI and Swagger for Spring Boot Applications.

    Swagger is a set of open-source tools that help you to describe REST-based APIs. This gives you the luxury to automatically build beautiful and interactive API documentation, automatically generate client libraries for your API in many languages, and explore other possibilities like automated testing.

    To begin working with OpenAPI and creating your first swagger document you will need the following dependency in your application.

    <dependency>     
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
    </dependency>

    Having version 3.0.0 of the starter make sure you have the compatible version of the starter parent dependency. in my case, I am using 2.4.0.

    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.0</version>
    </parent>

    Now having these dependencies all in place you need to provide the Docket bean to start serving the open API documentation endpoint. To do that you can add the following configuration with the given method with @Bean annotation.

    @Configuration
    public class SwaggerConfig
    @Bean
    public Docket getDocket()
    return new Docket(DocumentationType.SWAGGER_2)
    .select()
    .apis(RequestHandlerSelectors.any())
    .paths(PathSelectors.any())
    .build();

    The select() method will return ApiSelectorBuilder which can be used to manage the exposed swagger endpoints. In case you want the documentation for a specific path or package you can change the input for the related methods.

    return new Docket(DocumentationType.SWAGGER_2)
    .select()
    .apis(RequestHandlerSelectors.basePackage("fp.sw.controller"))
    .paths(PathSelectors.regex("/student/*"))
    .build();

    in our case, we used any() which will result in documenting all APIs. After preparing The Docket bean and running the application you can get the machine-readable version of the APIs documents in JSON format using the following endpoint.

    http://localhost:8080/v2/api-docs
    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022 1*KFkdgc28aelAQaIe R4VHQ

    Now to have a human-readable version and some extra features for testing we can use the swagger-UI dependency. The only thing you need to do to have it is to add the following dependency in your POM file.

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

    If you run your application after adding this dependency and visit the URL below, you will find a web-based GUI that describes the API and gives you the functionality to test your APIs.

    http://localhost:8080/swagger-ui/
    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022 1*tjSiMxMR mqTXiYpsNcpcQ

    On this page by default and based on your Docket configuration you will see a list of controllers. If you extend the controller you will find a list of valid methods (GET, POST, PUT, DELETE, HEAD, OPTIONS) as you defined inside the controller. By extending each method you will the useful data about the parameters list, content type, response status, and ..

    Documentation with Annotations

    To have some more details about each method, parameters, and the rest of the involved entities you can use a set of annotations to add comments which will later be rendered in the UI by swagger. Here are some of the most used annotations for documenting the APIs via swagger:

    @ApiOperation — using this annotation on the method you can add some description for that method and it will appear next to the path of the endpoint in the swagger UI.

    @GetMapping("/id")
    @ApiOperation(value="Getting student user information")
    public ResponseEntity<Student> getStudent(
    ...
    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022 1*or r10MbfGwboBK82aBodg
    @ApiOperation annotation in swagger-UI

    @ApiParam— This annotation will be used to describe the parameters in the requested method.

    @GetMapping("/id")
    public
    ResponseEntity<Student> getStudent(
    @ApiParam(value = "Student ID number" , required = true , example = "1")
    @PathVariable Long id ){
    ...
    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022 1*8DL8Ld OOec1FcyYEXMC9w
    @GetMapping annotation in swagger-UI

    @ApiModelProperty — can be used to describe properties in the model which are used as a request or response object.

    public class Student 
    @ApiModelProperty(notes = "Student Id Number",
    example = "1", position = 1)
    private Long id;

    @ApiModelProperty(notes = "Student name",
    example = "John", position = 2)
    private String name;

    Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022 1*DPUOBrzo8mZ8NWO79SijEQ
    @ApiModelProperty annotation in swagger-UI

    You can find the complete list here.

    Securing Swagger

    Because you are exposing some sensitive information via swagger it is recommended to disable the swagger in the production environment or at least secure it. To secure it you can use Spring Security and add the related started and by default, the swagger endpoints will be secured with basic authentication methods. You have a lot of flexible options in Spring Security for authentication and authorization which you can utilize.

    Generate Client Libraries

    Another benefit of using swagger is that you can use the OpenAPI Swagger spec to generate client libraries or SDKs in different languages. Swagger Codegen is one of the tools that can be used to create these libraries. Swagger Codegen can simplify your build process by generating server stubs and client SDKs for any API, defined with the OpenAPI (formerly known as Swagger) specification, so your team can focus better on your API’s implementation and adoption. While the tool quickly generates client libraries in 40 different languages, it also integrates with SwaggerHub. This makes collaboration much easier via the tool’s cloud interface.

    Automated Testing

    Having a machine-readable Swagger spec of your APIs gives you the possibility to use other applications to prepare the automated tests. Tools like Assertible and Postman can be used to import the Swagger spec and automatically create tests and assertions for every endpoint and method.

    2022 and api boot CES21 documentations farzin good jun, pashaee programming spring swagger writing
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Swave Digest
    • Website
    • Twitter
    • Pinterest

    Related Posts

    Travis Barker & Kourtney Kardashian Speak Out After He Was Hospitalized With ‘Life Threatening Pancreatitis’

    July 3, 2022

    Independence Day, The Founders And Bitcoin

    July 3, 2022

    TNN April Travel Book Club “Hitching for Hope: A Journey into the Heart and Soul of Ireland”

    July 3, 2022

    Man Found at Taylor Swift’s NYC Home Faces Stalking Charges – Billboard

    July 3, 2022
    Add A Comment

    Leave A Reply Cancel Reply

    Twitter Instagram Pinterest
    • Home
    • Privacy Policy
    • Terms & Conditions
    • Contact Us
    © 2022 Swave Digest. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.

    Posting....
    We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
    In case of sale of your personal information, you may opt out by using the link Do not sell my personal information.
    Cookie settingsACCEPT
    Manage consent

    Privacy Overview

    This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
    Necessary
    Always Enabled
    Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
    CookieDurationDescription
    cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
    cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
    cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
    cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
    cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
    viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
    Functional
    Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
    Performance
    Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
    Analytics
    Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
    Advertisement
    Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
    Others
    Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
    Save & Accept