Finatra-swagger: Making the api documentation awesome and easy

Finatra-swagger
Reading Time: 3 minutes

Apart from speed, high-performance, fault-tolerance and concurrency, one more most important feature for an api is a clean, precise, interactive and user friendly documentation. Documentation plays a very important role in a rest api. The interactive documentation makes api more easy and understandable. Finatra is fast, testable, Scala services built on Twitter-Server and Finagle, similarly Swagger is a well known api documentation framework. In this blog we are going to discuss how to integrate Swagger UI (Api documentation) with Finatra to achieve awesome and easy documentation with high performance and concurrency.

Getting started:

There are many libraries available for swagger finatra support. For this example we are using swagger-finatra.

Let’s start implementing finatra-swagger sample application:

Step 1: Dependencies:

Here are the dependencies for finatra-swagger sample:

Scala: 2.12.0
Finatra-http: 2.10.0
Finatra-swagger: 2.9.0

Step 2: Build.sbt:

Here is the build.sbt for this sample project:

name := "finatra-swagger-sample"

version := "1.0"
scalaVersion := "2.12.0"
lazy val versions = new {
  val finatra = "2.2.0"
  val swagger = "0.7.2"
}
resolvers ++= Seq(
  Resolver.sonatypeRepo("releases"),
  "Twitter Maven" at "https://maven.twttr.com"
)
resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/releases/"
libraryDependencies += "com.twitter" %% "finatra-http" % "2.10.0" % "compile"
libraryDependencies += "com.jakehschwartz" % "finatra-swagger_2.12" % "2.9.0" % "compile"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.3" % "test"

Step 3: Create a subclass of a SwaggerModule:

First of all, we need to create an object of swagger module to define basic information regarding api.
Here we need to create an object SampleSwaggerModule extending SwaggerModule which is defined under finatra-swagger library.
We can also define the api root information inside Swagger object using the Info object. The basic information defined can be description, version and title of  the api. You can see this information on top of the swagger document after running the application.
The security definition is used to add basic authentication inside swagger documentation if the api requires basic authentication.

object SampleSwaggerModule extends SwaggerModule {
  val swaggerUI = new Swagger()
  @Provides
  def swagger: Swagger = {
    val info = new Info()
      .description("The Knoldus / Knolder management API, this is a sample for swagger document generation")
      .version("1.0.1")
      .title("Knoldus / Knolder Management API")
    swaggerUI
      .info(info)
      .addSecurityDefinition("sampleBasic", {
        val d = new BasicAuthDefinition()
        d.setType("basic")
        d
      })
    swaggerUI
  }
}

Step 4: Add DocsController into server:

DocsController is a class defined in finatra-swagger library which works as a glue between finatra server and swagger.
If you have used finatra earlier, you must be familiar with finatra HttpServer and how to configure http routes inside finatra servers.
Here we are adding DocsController with SampleController. SampleController include the actual application routes with swagger related descriptions.

object SampleApp extends HttpServer {

  override def configureHttp(router: HttpRouter) {
    router
      .add[DocsController]
      .add[SampleController]
  }
  override protected def modules = Seq(SampleSwaggerModule)
}

Step 5: Configure the endpoints using the SwaggerRouteDSL:

Finally, we have to configure the endpoints using SwaggerRoteDSL. To do that we have to extends SwaggerController which is defined in the finatra-swagger library and inject Swagger as a dependency.
To define a route instead of using get we are using getWithDoc method and passing route information like route summary, tag, parameter type and response type etc.

class SampleController@Inject()(s: Swagger) extends SwaggerController {
  implicit protected val swagger = s

  getWithDoc("/knolder/:id") { id =>
    id.summary("Read the detail information about the knolder")
      .tag("Knolder")
      .routeParam[String]("id", "the knolder id")
      .responseWith[Knolder](200, "the knolder details")
      .responseWith(404, "the knolder not found")
  } { (request: Request) =>
    val knolderId: Int = request.getParam("id").toInt
    Knolder(Some(knolderId), "girish", "Consultant")
  }
}

All the options for http calls like get, post, delete and put are available. You can find a full http CRUD application sample on the git repo:

finatra-swagger-sample-app

Step 6: Running the application:

After finishing above steps we are ready to run the application and play with swagger document.

A. Clone git repo:

To run the app you can clone the git repo using the following command:

git clone git@github.com:knoldus/finatra-swagger-sample-app.git

B. Running application:

You can run the  application using the following command:

sbt run

C. Hitting rest end points on the browser:

Once the application is running you can go to browser and hit the url:

http://localhost:8888/knolder/1234

After hitting the end point you will see a sample response on the browser.

D. Analyzing swagger document:

Once the routes are working as expected you can find the swagger document by navigating to url:

http://localhost:8888/docs

Here is a screen shot of swagger doc generated for this sample application:

swagger-finatra

To explore more, please go through the application here.

Thanks!

Refrences:
finatra
swagger-ui
jakehschwartz/finatra-swagger

KNOLDUS-advt-sticker

Written by 

Girish is a Software Consultant, with experience of more than 3.5 years. He is a scala developer and very passionate about his interest towards Scala Eco-system. He has also done many projects in different languages like Java and Asp.net. He can work in both supervised and unsupervised environment and have a craze for computers whether working or not, he is almost always in front of his laptop's screen. His hobbies include reading books and listening to music. He is self motivated, dedicated and focused towards his work. He believes in developing quality products. He wants to work on different projects and different domains. He is curious to gain knowledge of different domains and try to provide solutions that can utilize resources and improve performance. His personal interests include reading books, video games, cricket and social networking. He has done Masters in Computer Applications from Lal Bahadur Shastri Institute of Management, New Delhi.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading