Swagger
Sangeeta Gulia
Software Consultant
Knoldus Software LLP
AGENDA
➔
What’s Swagger?
➔
Why Swagger?
➔
Swagger Components
➔
Data Types
➔
Generating Swagger Spec
➔
Getting started with Play-Swagger
➔
Important Attributes
➔
Swagger Codegen
➔
Generating SDKs
What’s Swagger?
● The goal of Swagger is to define a standard, language-agnostic interface to
REST APIs which allows both humans and computers to discover and
understand the capabilities of the service without access to source code,
documentation.
● When properly defined via Swagger, a consumer can understand and interact
with the remote service with a minimal amount of implementation logic.
● It can be visualised similar to what interfaces have done for lower-level
programming
● Swagger removes the guesswork in calling the service.
Why Swagger?
Swagger is one of the most popular specifications for REST APIs for a number
of reasons:
1.Swagger generates an interactive API console for people to quickly learn
about and try the API.
2.Swagger generates the client SDK code needed for implementations on
various platforms.
3.The Swagger file can be auto-generated from code annotations or using
case class definitions on a lot of different platforms.
4.Swagger has a strong community with helpful contributors.
Swagger Components
● Swagger spec: The Swagger spec is the official schema about name and
element nesting, order, and so on. If you plan on hand-coding the Swagger
files, you’ll need to be extremely familiar with the Swagger spec.
● Swagger editor: The Swagger Editor is an online editor that validates your
YML-formatted content against the rules of the Swagger spec. YML is a syntax
that depends on spaces and nesting. You’ll need to be familiar with YML
syntax and the rules of the Swagger spec to be successful here. The Swagger
editor will flag errors and give you formatting tips. (Note that the Swagger spec
file can be in either JSON or YAML format.)
Example: http://editor.swagger.io/#/
Swagger Components(cont...)
● Swagger-UI: The Swagger UI is an HTML/CSS/JS framework that parses a
JSON or YML file that follows the Swagger spec and generates a navigable UI
of the documentation.
● Swagger-codegen: This utility generates client SDK code for a lot of different
platforms (such as Java, JavaScript, Scala, Python, PHP, Ruby, Scala, and
more). This client code helps developers integrate your API on a specific
platform and provides for more robust implementations that might include
more scaling, threading, and other necessary code. An SDK is supportive
tooling that helps developers use the REST API.
Data Types
Note: Primitives have an optional modifier property format.
Generating Swagger Spec
● Two Techniques:
1) Using Annotations
2) Using iheart’s play-swagger
(A library that generates swagger specs from route files and case class
reflection, no code annotation needed.)
Getting started with play-swagger
● Step – 1 : Add dependency to build.sbt.
libraryDependencies += "com.iheart" %% "play-swagger" % "0.4.0"
● Step – 2 : Add a base swagger.yml (or swagger.json) to the resources (for
example, conf folder in the play application).
This one needs to provide all the required fields according to swagger spec.
Getting started with play-swagger (cont...)
Basic swagger.json
{
"swagger": "2.0",
"host": "localhost:9000",
"consumes": [
"application/json",
"application/text"
],
"produces": [
"application/json"
]
}
Getting started with play-swagger (cont..)
● Step – 3 : You can use swagger-ui webjar and have your play app serving the
swagger ui:
Add the following dependency:
libraryDependencies += "org.webjars" % "swagger-ui" % "2.1.4"
● Step – 4 : Add the following to your routes file:
### NoDocs ###
GET /swagger.json controllers.ApiSpecs.specs
### NoDocs ###
GET /docs/*file controllers.Assets.versioned(path:String=
"/public/lib/swagger-ui", file:String)
Getting started with play-swagger (cont..)
● Step – 5 : Now we need to create the controller(ApiSpecs as mentioned in
routes) who will be responsible for generating spec file, reading required things
from routes file and models(i.e case classes).
--------------------------------------------------------------------------------------------------------
ApiSpecs.scala
--------------------------------------------------------------------------------------------------------
import play.api.libs.concurrent.Execution.Implicits._
import com.iheart.playSwagger.SwaggerSpecGenerator
import play.api.mvc.{Action, Controller}
import scala.concurrent.Future
class ApiSpecs extends Controller {
implicit val cl = getClass.getClassLoader
val domainPackage = "models"
private lazy val generator = SwaggerSpecGenerator(domainPackage)
def specs = Action.async { _ =>
Future.fromTry(generator.generate()).map(Ok(_))
}
}
Getting started with play-swagger (cont..)
● SwaggerSpecGenerator is a case class which takes DomainModelQualifier,
which in turn accepts namespace*.
● Generate is the method which takes location of route file as argument.
(Note: if not specified, by default it uses conf/routes)
● Now you can see the generated swagger UI at :
http://localhost:9000/docs/index.html?url=/swagger.json#/
Important Attributes
S. No. Attribute Name Description
1 tags Used to group multiple routes.
2 summary Describe short summary about route.
3 consumes Determine the type of data being accepted by any route.
4 produces Determine the type of data being returned as response.
5 parameters Define the parameters(including attributes type, format, required,
description, in). It hold array of parameters.
6 responses Define the schema of responses as per different response codes
7 schema Define schema of response
8 description Used to provide description for a route, any parameter or any
response.
9 required Used to denote if a parameter is required or not. (default: false)
How to hide an endpoint?
If you don't want an end point to be included, add ### NoDocs ### in front of it
e.g.
### NoDocs ###
GET /docs/swagger-ui/*file
controllers.Assets.at(path:String="/public/lib/swagger-ui", file:String)
Specify parameters in query
###
# {
# "tags" : ["QueryStringContainData"],
# "summary" : "get student record(query example)",
# "parameters" : [ {
# "in" : "query",
# "name":"id",
# "description": "Student Id",
# "required":true,
# "type":"string"
# } ],
# "responses": {
# "200": {
# "description": "success",
# "schema": { "$ref": "#/definitions/models.StudentRecordResponse" }
# }
# }
# }
###
GET /get/student/record/
controllers.SwaggerUiController.getStudentRecordById
Specify parameters in path
###
# {
# "tags" : ["PathContainData"],
# "summary" : "get student record(path example)",
# "parameters" : [ {
# "in" : "path",
# "name":"id",
# "description": "Student Id",
# "required":true,
# "type":"string"
# } ],
# "responses": {
# "200": {
# "description": "success",
# "schema": { "$ref": "#/definitions/models.StudentRecordResponse" }
# }
# }
# }
###
GET /student/record/:id
controllers.SwaggerUiController.getRecordById(id: Int)
Specify parameters as formUrlEncodedBody
###
● # {
● # "tags" : ["BodyData"],
● # "summary" : "mirror response",
● # "consumes" : [ "application/x-www-form-urlencoded" ],
● # "parameters" : [ {
● # "in" : "formData",
● # "name":"id",
● # "description": "Employee Id",
● # "required":true,
● # "type":"integer",
● # "format":"int64"
● # } ],
● # "responses": {
● # "200": {
● # "description": "success",
● # "schema": { "$ref": "#/definitions/models.RequestWithBody" }
● # }
● # }
● # }
● ###
Sending Multipart form data
###
# {
# "tags" : ["Multipart Data"],
# "summary" : "multipart data",
# "consumes" : [ "multipart/form-data" ],
# "parameters" : [
# {
# "in" : "formData",
# "name":"key",
# "required":true,
# "type":"string"
# },
# ],
# "responses": {
# "200": {
# "description": "success",
# "schema": {
# "$ref": "#/definitions/models.swagger.Response"
# }
# }
# }
# }
###
Specify response definition in Swagger.json
“definitions”: {
"InternRecordResponse" : {
"type":"object",
"required":[ "data" ],
"properties": {
"data" : {
"$ref": "#/definitions/InternRecord"
}
}
},
"InternRecord": {
"type":"object",
"properties": {
"intern_id" : { "type": "string" },
"intern_email" : { "type": "string" }
}
}
}
USAGE:
"$ref": "#/definitions/InternRecordResponse"
Specify response details
# "responses": {
# "200": {
# "description": "success",
# "schema": {
# "$ref": "#/definitions/models.RequestWithBody"
# }
# },
# "400": {
# "description": "Problem in parsing input json data",
# "schema": {
# "$ref": "#/definitions/models.ErrorResponse"
# }
# },
# "default": {
# "description": "error",
# "schema": {
# "$ref": "#/definitions/models.ErrorResponse"
# }
# }
# }
Handling Option field on UI
We can have optional field, but on UI it can be identified under Model tab and not
in model schema.
This feature is yet to be included.
Swagger Codegen
swagger-codegen contains a template-driven engine to generate
documentation, API clients and server stubs in different languages by parsing
your OpenAPI / Swagger definition.
Generating SDKs
git clone https://github.com/swagger-api/swagger-codegen
cd swagger-codegen
mvn clean package
Command to create SDK:
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar
generate 
-i http://petstore.swagger.io/v2/swagger.json 
-l php 
-o /var/tmp/php_api_client
Demo
Demo project can be found at :
https://github.com/knoldus/swagger-demo
Introduction to Swagger
Thank You...
➔
https://github.com/iheartradio/play-swagger
➔
https://github.com/swagger-api/swagger-codegen
References

More Related Content

PPTX
API Docs with OpenAPI 3.0
PPTX
Introducing Swagger
PPTX
An Introduction To REST API
PDF
OpenAPI 3.0, And What It Means for the Future of Swagger
DOCX
373512722-Employee-Leave-Management-System.docx
PPTX
Introducing OpenAPI Version 3.1
PPTX
Introducing MongoDB Atlas
API Docs with OpenAPI 3.0
Introducing Swagger
An Introduction To REST API
OpenAPI 3.0, And What It Means for the Future of Swagger
373512722-Employee-Leave-Management-System.docx
Introducing OpenAPI Version 3.1
Introducing MongoDB Atlas

What's hot (20)

PPTX
What is Swagger?
PDF
Swagger / Quick Start Guide
PDF
Documenting your REST API with Swagger - JOIN 2014
PPTX
Rest API with Swagger and NodeJS
PDF
Swagger With REST APIs.pptx.pdf
PDF
Designing APIs with OpenAPI Spec
PDF
Spring Security
PPTX
REST API Design & Development
PPTX
PDF
Introduction to ASP.NET Core
PPTX
Introduction to GraphQL Presentation.pptx
PPT
Graphql presentation
PDF
Swagger UI
PPTX
Swagger APIs for Humans and Robots (Gluecon)
PPTX
Introduction to REST - API
PPSX
Rest api standards and best practices
PDF
What is REST API? REST API Concepts and Examples | Edureka
PPTX
Json Web Token - JWT
PPTX
Spring Security 5
PDF
Laravel Introduction
What is Swagger?
Swagger / Quick Start Guide
Documenting your REST API with Swagger - JOIN 2014
Rest API with Swagger and NodeJS
Swagger With REST APIs.pptx.pdf
Designing APIs with OpenAPI Spec
Spring Security
REST API Design & Development
Introduction to ASP.NET Core
Introduction to GraphQL Presentation.pptx
Graphql presentation
Swagger UI
Swagger APIs for Humans and Robots (Gluecon)
Introduction to REST - API
Rest api standards and best practices
What is REST API? REST API Concepts and Examples | Edureka
Json Web Token - JWT
Spring Security 5
Laravel Introduction
Ad

Viewers also liked (20)

ODP
An Introduction to Akka http
ODP
Akka Finite State Machine
ODP
Introduction to AWS IAM
PDF
iHeartMedia_Millennials
PDF
次世代セキュリティを牽引する画像解析技術の最新動向 - 距離情報を用いた物体認識技術 -
ODP
Drilling the Async Library
ODP
Introduction to Scala JS
ODP
Akka streams
ODP
Getting Started With AureliaJs
ODP
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
ODP
String interpolation
ODP
Realm Mobile Database - An Introduction
ODP
Shapeless- Generic programming for Scala
PDF
Kanban
ODP
Introduction to Java 8
ODP
An Introduction to Quill
ODP
Introduction to Scala Macros
ODP
Mandrill Templates
ODP
Introduction to ScalaZ
ODP
ANTLR4 and its testing
An Introduction to Akka http
Akka Finite State Machine
Introduction to AWS IAM
iHeartMedia_Millennials
次世代セキュリティを牽引する画像解析技術の最新動向 - 距離情報を用いた物体認識技術 -
Drilling the Async Library
Introduction to Scala JS
Akka streams
Getting Started With AureliaJs
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
String interpolation
Realm Mobile Database - An Introduction
Shapeless- Generic programming for Scala
Kanban
Introduction to Java 8
An Introduction to Quill
Introduction to Scala Macros
Mandrill Templates
Introduction to ScalaZ
ANTLR4 and its testing
Ad

Similar to Introduction to Swagger (20)

PDF
Go swagger tutorial how to create golang api documentation using go swagger (1)
PDF
Wt unit 2 ppts client side technology
PDF
Wt unit 2 ppts client sied technology
PDF
AEM Sightly Deep Dive
PPTX
HNDIT1022 Week 08, 09 10 Theory web .pptx
PDF
8.-Javascript-report powerpoint presentation
PDF
Simplify React App Login with Asgardeo React SDK
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
PPTX
MongoDB Days UK: Building Apps with the MEAN Stack
PDF
Introduction to angular js
PDF
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
PDF
exploring-spring-boot-clients.pdf Spring Boot
PDF
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
PDF
Get Hip with JHipster - GIDS 2019
PDF
JS BASICS JAVA SCRIPT SCRIPTING
PDF
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
PDF
Quick run in with Swagger
PDF
JavaScript - Chapter 3 - Introduction
PPTX
Google Apps Script for Beginners- Amazing Things with Code
Go swagger tutorial how to create golang api documentation using go swagger (1)
Wt unit 2 ppts client side technology
Wt unit 2 ppts client sied technology
AEM Sightly Deep Dive
HNDIT1022 Week 08, 09 10 Theory web .pptx
8.-Javascript-report powerpoint presentation
Simplify React App Login with Asgardeo React SDK
WebNet Conference 2012 - Designing complex applications using html5 and knock...
MongoDB Days UK: Building Apps with the MEAN Stack
Introduction to angular js
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
exploring-spring-boot-clients.pdf Spring Boot
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Get Hip with JHipster - GIDS 2019
JS BASICS JAVA SCRIPT SCRIPTING
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Quick run in with Swagger
JavaScript - Chapter 3 - Introduction
Google Apps Script for Beginners- Amazing Things with Code

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Recently uploaded (20)

PPTX
Airline CRS | Airline CRS Systems | CRS System
PDF
The Dynamic Duo Transforming Financial Accounting Systems Through Modern Expe...
PDF
MCP Security Tutorial - Beginner to Advanced
PPTX
Viber For Windows 25.7.1 Crack + Serial Keygen
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PPTX
Tech Workshop Escape Room Tech Workshop
PDF
E-Commerce Website Development Companyin india
PPTX
Computer Software - Technology and Livelihood Education
PPTX
Download Adobe Photoshop Crack 2025 Free
PDF
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
DOCX
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
PPTX
Lecture 5 Software Requirement Engineering
PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PDF
Visual explanation of Dijkstra's Algorithm using Python
PDF
Internet Download Manager IDM Crack powerful download accelerator New Version...
PPTX
Introduction to Windows Operating System
PDF
Workplace Software and Skills - OpenStax
PPTX
HackYourBrain__UtrechtJUG__11092025.pptx
PDF
novaPDF Pro 11.9.482 Crack + License Key [Latest 2025]
PDF
Multiverse AI Review 2025: Access All TOP AI Model-Versions!
Airline CRS | Airline CRS Systems | CRS System
The Dynamic Duo Transforming Financial Accounting Systems Through Modern Expe...
MCP Security Tutorial - Beginner to Advanced
Viber For Windows 25.7.1 Crack + Serial Keygen
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
Tech Workshop Escape Room Tech Workshop
E-Commerce Website Development Companyin india
Computer Software - Technology and Livelihood Education
Download Adobe Photoshop Crack 2025 Free
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
Lecture 5 Software Requirement Engineering
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Visual explanation of Dijkstra's Algorithm using Python
Internet Download Manager IDM Crack powerful download accelerator New Version...
Introduction to Windows Operating System
Workplace Software and Skills - OpenStax
HackYourBrain__UtrechtJUG__11092025.pptx
novaPDF Pro 11.9.482 Crack + License Key [Latest 2025]
Multiverse AI Review 2025: Access All TOP AI Model-Versions!

Introduction to Swagger

  • 2. AGENDA ➔ What’s Swagger? ➔ Why Swagger? ➔ Swagger Components ➔ Data Types ➔ Generating Swagger Spec ➔ Getting started with Play-Swagger ➔ Important Attributes ➔ Swagger Codegen ➔ Generating SDKs
  • 3. What’s Swagger? ● The goal of Swagger is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation. ● When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. ● It can be visualised similar to what interfaces have done for lower-level programming ● Swagger removes the guesswork in calling the service.
  • 4. Why Swagger? Swagger is one of the most popular specifications for REST APIs for a number of reasons: 1.Swagger generates an interactive API console for people to quickly learn about and try the API. 2.Swagger generates the client SDK code needed for implementations on various platforms. 3.The Swagger file can be auto-generated from code annotations or using case class definitions on a lot of different platforms. 4.Swagger has a strong community with helpful contributors.
  • 5. Swagger Components ● Swagger spec: The Swagger spec is the official schema about name and element nesting, order, and so on. If you plan on hand-coding the Swagger files, you’ll need to be extremely familiar with the Swagger spec. ● Swagger editor: The Swagger Editor is an online editor that validates your YML-formatted content against the rules of the Swagger spec. YML is a syntax that depends on spaces and nesting. You’ll need to be familiar with YML syntax and the rules of the Swagger spec to be successful here. The Swagger editor will flag errors and give you formatting tips. (Note that the Swagger spec file can be in either JSON or YAML format.) Example: http://editor.swagger.io/#/
  • 6. Swagger Components(cont...) ● Swagger-UI: The Swagger UI is an HTML/CSS/JS framework that parses a JSON or YML file that follows the Swagger spec and generates a navigable UI of the documentation. ● Swagger-codegen: This utility generates client SDK code for a lot of different platforms (such as Java, JavaScript, Scala, Python, PHP, Ruby, Scala, and more). This client code helps developers integrate your API on a specific platform and provides for more robust implementations that might include more scaling, threading, and other necessary code. An SDK is supportive tooling that helps developers use the REST API.
  • 7. Data Types Note: Primitives have an optional modifier property format.
  • 8. Generating Swagger Spec ● Two Techniques: 1) Using Annotations 2) Using iheart’s play-swagger (A library that generates swagger specs from route files and case class reflection, no code annotation needed.)
  • 9. Getting started with play-swagger ● Step – 1 : Add dependency to build.sbt. libraryDependencies += "com.iheart" %% "play-swagger" % "0.4.0" ● Step – 2 : Add a base swagger.yml (or swagger.json) to the resources (for example, conf folder in the play application). This one needs to provide all the required fields according to swagger spec.
  • 10. Getting started with play-swagger (cont...) Basic swagger.json { "swagger": "2.0", "host": "localhost:9000", "consumes": [ "application/json", "application/text" ], "produces": [ "application/json" ] }
  • 11. Getting started with play-swagger (cont..) ● Step – 3 : You can use swagger-ui webjar and have your play app serving the swagger ui: Add the following dependency: libraryDependencies += "org.webjars" % "swagger-ui" % "2.1.4" ● Step – 4 : Add the following to your routes file: ### NoDocs ### GET /swagger.json controllers.ApiSpecs.specs ### NoDocs ### GET /docs/*file controllers.Assets.versioned(path:String= "/public/lib/swagger-ui", file:String)
  • 12. Getting started with play-swagger (cont..) ● Step – 5 : Now we need to create the controller(ApiSpecs as mentioned in routes) who will be responsible for generating spec file, reading required things from routes file and models(i.e case classes). -------------------------------------------------------------------------------------------------------- ApiSpecs.scala -------------------------------------------------------------------------------------------------------- import play.api.libs.concurrent.Execution.Implicits._ import com.iheart.playSwagger.SwaggerSpecGenerator import play.api.mvc.{Action, Controller} import scala.concurrent.Future class ApiSpecs extends Controller { implicit val cl = getClass.getClassLoader val domainPackage = "models" private lazy val generator = SwaggerSpecGenerator(domainPackage) def specs = Action.async { _ => Future.fromTry(generator.generate()).map(Ok(_)) } }
  • 13. Getting started with play-swagger (cont..) ● SwaggerSpecGenerator is a case class which takes DomainModelQualifier, which in turn accepts namespace*. ● Generate is the method which takes location of route file as argument. (Note: if not specified, by default it uses conf/routes) ● Now you can see the generated swagger UI at : http://localhost:9000/docs/index.html?url=/swagger.json#/
  • 14. Important Attributes S. No. Attribute Name Description 1 tags Used to group multiple routes. 2 summary Describe short summary about route. 3 consumes Determine the type of data being accepted by any route. 4 produces Determine the type of data being returned as response. 5 parameters Define the parameters(including attributes type, format, required, description, in). It hold array of parameters. 6 responses Define the schema of responses as per different response codes 7 schema Define schema of response 8 description Used to provide description for a route, any parameter or any response. 9 required Used to denote if a parameter is required or not. (default: false)
  • 15. How to hide an endpoint? If you don't want an end point to be included, add ### NoDocs ### in front of it e.g. ### NoDocs ### GET /docs/swagger-ui/*file controllers.Assets.at(path:String="/public/lib/swagger-ui", file:String)
  • 16. Specify parameters in query ### # { # "tags" : ["QueryStringContainData"], # "summary" : "get student record(query example)", # "parameters" : [ { # "in" : "query", # "name":"id", # "description": "Student Id", # "required":true, # "type":"string" # } ], # "responses": { # "200": { # "description": "success", # "schema": { "$ref": "#/definitions/models.StudentRecordResponse" } # } # } # } ### GET /get/student/record/ controllers.SwaggerUiController.getStudentRecordById
  • 17. Specify parameters in path ### # { # "tags" : ["PathContainData"], # "summary" : "get student record(path example)", # "parameters" : [ { # "in" : "path", # "name":"id", # "description": "Student Id", # "required":true, # "type":"string" # } ], # "responses": { # "200": { # "description": "success", # "schema": { "$ref": "#/definitions/models.StudentRecordResponse" } # } # } # } ### GET /student/record/:id controllers.SwaggerUiController.getRecordById(id: Int)
  • 18. Specify parameters as formUrlEncodedBody ### ● # { ● # "tags" : ["BodyData"], ● # "summary" : "mirror response", ● # "consumes" : [ "application/x-www-form-urlencoded" ], ● # "parameters" : [ { ● # "in" : "formData", ● # "name":"id", ● # "description": "Employee Id", ● # "required":true, ● # "type":"integer", ● # "format":"int64" ● # } ], ● # "responses": { ● # "200": { ● # "description": "success", ● # "schema": { "$ref": "#/definitions/models.RequestWithBody" } ● # } ● # } ● # } ● ###
  • 19. Sending Multipart form data ### # { # "tags" : ["Multipart Data"], # "summary" : "multipart data", # "consumes" : [ "multipart/form-data" ], # "parameters" : [ # { # "in" : "formData", # "name":"key", # "required":true, # "type":"string" # }, # ], # "responses": { # "200": { # "description": "success", # "schema": { # "$ref": "#/definitions/models.swagger.Response" # } # } # } # } ###
  • 20. Specify response definition in Swagger.json “definitions”: { "InternRecordResponse" : { "type":"object", "required":[ "data" ], "properties": { "data" : { "$ref": "#/definitions/InternRecord" } } }, "InternRecord": { "type":"object", "properties": { "intern_id" : { "type": "string" }, "intern_email" : { "type": "string" } } } } USAGE: "$ref": "#/definitions/InternRecordResponse"
  • 21. Specify response details # "responses": { # "200": { # "description": "success", # "schema": { # "$ref": "#/definitions/models.RequestWithBody" # } # }, # "400": { # "description": "Problem in parsing input json data", # "schema": { # "$ref": "#/definitions/models.ErrorResponse" # } # }, # "default": { # "description": "error", # "schema": { # "$ref": "#/definitions/models.ErrorResponse" # } # } # }
  • 22. Handling Option field on UI We can have optional field, but on UI it can be identified under Model tab and not in model schema. This feature is yet to be included.
  • 23. Swagger Codegen swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
  • 24. Generating SDKs git clone https://github.com/swagger-api/swagger-codegen cd swagger-codegen mvn clean package Command to create SDK: java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i http://petstore.swagger.io/v2/swagger.json -l php -o /var/tmp/php_api_client
  • 25. Demo Demo project can be found at : https://github.com/knoldus/swagger-demo