SlideShare ist ein Scribd-Unternehmen logo
1 von 28
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
Thank You...
➔
https://github.com/iheartradio/play-swagger
➔
https://github.com/swagger-api/swagger-codegen
References

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Designing APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecDesigning APIs with OpenAPI Spec
Designing APIs with OpenAPI Spec
 
Document your rest api using swagger - Devoxx 2015
Document your rest api using swagger - Devoxx 2015Document your rest api using swagger - Devoxx 2015
Document your rest api using swagger - Devoxx 2015
 
Swagger UI
Swagger UISwagger UI
Swagger UI
 
Mock Server Using WireMock
Mock Server Using WireMockMock Server Using WireMock
Mock Server Using WireMock
 
API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Postman.ppt
Postman.pptPostman.ppt
Postman.ppt
 
OpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerOpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of Swagger
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessible
 
API for Beginners
API for BeginnersAPI for Beginners
API for Beginners
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
 
Api types
Api typesApi types
Api types
 
What is an API
What is an APIWhat is an API
What is an API
 
Postman
PostmanPostman
Postman
 
Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface)
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
Pentesting ReST API
Pentesting ReST APIPentesting ReST API
Pentesting ReST API
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Spring Security
Spring SecuritySpring Security
Spring Security
 

Andere mochten auch

iHeartMedia_Millennials
iHeartMedia_MillennialsiHeartMedia_Millennials
iHeartMedia_Millennials
Petra Estep
 

Andere mochten auch (20)

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

Ähnlich wie Introduction to Swagger

WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
Fabio Franzini
 
cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123
Parag Gajbhiye
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 

Ähnlich wie Introduction to Swagger (20)

Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)Go swagger tutorial how to create golang api documentation using go swagger (1)
Go swagger tutorial how to create golang api documentation using go swagger (1)
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
MongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN StackMongoDB Days UK: Building Apps with the MEAN Stack
MongoDB Days UK: Building Apps with the MEAN Stack
 
cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123cdac@parag.gajbhiye@test123
cdac@parag.gajbhiye@test123
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James WilliamsSF Grails - Ratpack - Compact Groovy Webapps - James Williams
SF Grails - Ratpack - Compact Groovy Webapps - James Williams
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019Get Hip with JHipster - GIDS 2019
Get Hip with JHipster - GIDS 2019
 
JS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTINGJS BASICS JAVA SCRIPT SCRIPTING
JS BASICS JAVA SCRIPT SCRIPTING
 
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
Maciej Treder "Server-side rendering with Angular—be faster and more SEO, CDN...
 
Quick run in with Swagger
Quick run in with SwaggerQuick run in with Swagger
Quick run in with Swagger
 
JavaScript - Chapter 3 - Introduction
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with Code
 
Grails 101
Grails 101Grails 101
Grails 101
 
Gapand 2017 - Diseñando Arquitecturas Serverless en Azure
Gapand 2017 - Diseñando Arquitecturas Serverless en AzureGapand 2017 - Diseñando Arquitecturas Serverless en Azure
Gapand 2017 - Diseñando Arquitecturas Serverless en Azure
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 

Mehr von Knoldus Inc.

Mehr von Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Kürzlich hochgeladen

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

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
  • 26.