Designing Spring boot REST API - Swagger tutorial


Designing REST API using swagger for a Spring Boot Application

Today we will learn about swagger which is a great helpful framework that save a lot of things in REST API development.

what swagger is used for

Most application build today use web services (RESTful or SOAP) to fetch data from backend but REST API depends on HTTP methods and SOAP uses Web Services Description Language (WSDL) to description this request and response format which REST API is missing.

without a proper documentation its make odd for the team to collaborate especially when there are too many APIs that is where swagger comes in. 

Swagger is an open source framework that helps remedy these issues for teams. The framework provides the Open API Specification (formerly known as the Swagger specification) for creating RESTful API documentation formatted in JSON or YAML, a human-friendly also using swagger we can generated client code in various programming languages supported by swagger codegen which help us to save time we only need to implement the business logic for each endpoints API's.

What is WSDL?

WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information.

Swagger example 

Before we write our first swagger, you need to have a basic understanding of REST API. Open Swagger Editor 

We will design an employee management swagger which contain below endpoints to perform CURD operation.


HTTP Method

URL or resource

Description

GET

/employees

Fetch all employee information

GET

/employee/{id}

Fetch specific employee using employee id

POST

/employee

Add an employee details

PUT

/employee/{id}

Update an employee details

DELETE

/employee/{id}

Delete an employee


Swagger contain few pre-defined elements we can use in our API documentation.

Defining Basic information about our swagger

  • swagger: used to specific the Swagger version , which we are using.
  • info: contains the information about API like description, version of API, the title of API, term of services, and URL
    • description: It contains the high level information of API.
    • version: It shows the version of API.
    • title: It specifies the title of API.
    • termOfService: It specifies the term of service, if any.
    • contact: It specifies the contact detail of a person, if any.
    • license: It specifies the default license Apache 2.0.
  • host: used to host where we are hosting the service.
  • basePath: used in URI after the port number and before the API.
  • tags: We can assign tags to our resources. It is used to group resources in multiple categories.

swagger: "2.0"

info:
  description: "Employee management swagger which contain endpoint to perform CURD operations."
  version: "1.0.0"
  title: "Employee Management System"
  termsOfService: "http://swagger.io/terms/"
  contact:
    email: "xxx@xxxcompany.com"

host: "http://localhost:8080"
basePath: "/v2"

schemes:
- "https"
- "http"


Adding Authentication security

  • securityDefinitions: used to set security definitions for our API.
    • basic for Basic Authentication
    • apiKey when using an API key to secure the API
    • oauth2 for Oauth 2
  • Security: contain security definition applying to all endpoint in our swagger

  securityDefinitions:
  basicAuth:
    type: basic
  ApiKeyAuth:
    type: apiKey
    in: header
    name: X-API-Key
  OAuth2:
    type: oauth2
    flow: accessCode
    authorizationUrl: https://example.com/oauth/authorize
    tokenUrl: https://example.com/oauth/token
    scopes:
      read: Grants read access
      write: Grants write access
      admin: Grants read and write access to administrative information
Swagger basic and api key authentication  example

Swagger basic and OAuth2  authentication  example


Here I have added only basic authentication to security so all endpoint will have basic authentication.

security:
  - basicAuth: []


Defining parameter to use in endpoint

We have to define the parameters in parameter section inside path.a parameter have 3 thing's name, location(in), data type (scheme or content) which are mandatory.

Types of parameter

Based on the parameter type its location (in) attribute is determined.

  • Swagger path parameters -  Path parameters are variable parts of a URL path. Used to point to specific resource such as a user identified by ID.A URL can have several path parameters, each denoted with curly braces { } .ex /employee/{id} ,define location in:path to denote path parameter
  • Swagger query parameters - this parameter are the most common type of parameters and appear at the end of the request URL after a question mark (?), with different name=value pairs separated by ampersands (&). ex /employee?role=developer ,define location in:query to denote query parameter
  • Swagger header parameters - an endpoint may require many custom values this parameter can be sent in header define a location in as header to denote header parameters ex X-MyHeader: test111.

To make a parameter when calling an endpoint use required attribute as true.

parameters:
  x-requestId:
    name: x-requestid
    in: header
    description: used for logging purpose as unqiue idenfier
    type: string
    required: true
  employeeId:
    name: employeeid
    in: path
    description: employee id
    type: string
    required: true
  employeeRole:
    name: employeeRole
    in: query
    description: role assigned to each employee used to filter out employee based on their role.
    type: string
    required: true

Defining what we accept and return

Our endpoint may accept request in different format and response in different format we can specific what format our endpoint accept and return.

  consumes:
      - "application/json"
      - "application/xml"
      produces:
      - "application/xml"
      - "application/json"


Creating Request and response structure

Now we will create swagger request and response with the help of some swagger attributes.

swagger example spring boot employee curd example

 Employees:
    type: array
    items:
      $ref: "#/definitions/Employee"

  Employee:
    type: object
    properties:
      name:
        type: string
      jobTitle:
        type: string
      mobileNo:
        type: number
        minimum: 10
        maximum: 10
      joinedDate:
        type: "string"
        format: "date-time"
      gender:
        type: "string"
        enum:
          - "male"
          - "female"
          - "other"
      salary:
        type: number
        format: double
      deptId:
        $ref: '#/definitions/Department'
      projectId:
        $ref: '#/definitions/Project'

  Department:
    $ref: "#/definitions/Details"

  Project:
    $ref: "#/definitions/Details"

  Details:
    type: object
    properties:
      id:
        type: string
      name:
        type: string
swagger definitions model class example


Creating Endpoints 

swagger endpoint - an endpoint is a communication channel and this are channel are used when one API interact with other API.an endpoint can contain http method, URL and send(request) , receive(response).

  • paths: It specifies the path of resources that we are exposed and the different operations that can be performed on these resources.
  • definitions: It includes the distinct elements (basically class in programming term) that we have used in our API.
  • responses: It includes different response structure object for http code which are used in endpoints.

paths:
  /employees:
    get:
      tags:
      - "AllEmployees"
      summary: "Fetch all employee"
      parameters:
        - $ref: '#/parameters/x-requestId'
      responses:
        "200":
          description: "successful operation"
          schema:
              $ref: '#/definitions/Employees'
        "400":
          $ref: "#/responses/invalidRequest"
swagger endpoints path example

swagger editor is an online tool to design and edit swagger, enable to document, describe the API endpoints.

Swagger codepen is used to generated client side code out of swagger for different platform see Code generation using codegen

Post a Comment

Previous Post Next Post

Recent Posts

Facebook