SlideShare uma empresa Scribd logo
1 de 26
Baixar para ler offline
SWAGGER 2.0
Quick Start Guide
tech talk @ ferret
Andrii Gakhov
WHAT IS 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, or
through network traffic inspection.
• Swagger is a formal specification surrounded by a large
ecosystem of tools
SWAGGER ECOSYSTEM
• Swagger Editor

edit API specifications inYAML inside browser and preview
documentations in real time.
• Swagger Codegen

allows generation of both client libraries and server stubs from a
Swagger definition.
• Swagger UI

dependency-free collection of HTML, Javascript, and CSS assets that
dynamically generate beautiful documentation from a Swagger-
compliant API
http://swagger.io/tools/
USAGE PATTERNS FOR API PROVIDERS
Swagger
Editor
Swagger
Definition
Swagger
Codegen
Swagger
UI
API
Swagger Editor
Swagger
Definition
Swagger
Codegen
Swagger
UI
API
API
Swagger-Core
JAX-RS
Automatic
generation
top-down approach
bottom-up approach
SWAGGER SPECIFICATION
• The Swagger representation of the API is made of a single file
swagger.json (but can refer to other resources)
• Represented as JSON, butYAML can be used
• All field names are case sensitive
• Primitive data types in the Swagger Specification are based
on the types supported by the JSON-Schema Draft 4.
• Models are described using the Schema Object which is a
subset of JSON Schema Draft 4.
https://github.com/swagger-api/swagger-spec/
SWAGGER OBJECT
info
API metadata
paths
available paths and operations
definitions
data types produced and consumed by operations
parameters
parameters that can be used across operations
responses
responses that can be used across operations
securityDefinitions
security scheme definitions
security
alternative security schemes that can be used
tags
list of tags with additional metadata
externalDocs
additional external documentation
SWAGGER EDITOR EXAMPLE
SWAGGER UI EXAMPLE
SWAGGER UI EXAMPLE
COMMUNITY-DRIVEN LANGUAGE
INTEGRATIONS
• Clojure
• ColdFusion / CFML
• Eiffel
• Go
• Groovy
• Java
• JavaScript
• Node.js
• Perl
• PHP
• Python
• Ruby
• Scala
https://github.com/swagger-api/swagger-spec#additional-libraries
DEMO API
UNFORMAL SPECIFICATION
• We want to design DEMO API that can provide access to our database of
articles
• Every article in the database has a list of authors, so internally we have 2
main data objects:Article and Author
• All responses from our API should be made in JSON
• We want to able:
1. get all articles

GET /v1/articles
2. get all authors from the particular article

GET /v1/article/{id}/authors
SWAGGER DEFINITION METADATA
"swagger": "2.0",
"info": {
"title": "DEMO API",
"description": "Demonstration for techtalk @ ferret",
"version": "1.0.0"
},
"host": "api.demo.berlin",
"schemes": [
"http",
"https"
],
"basePath":“/v1",
“consumes”: [
“application/json”
],
"produces": [
"application/json"
],
SWAGGER DEFINITION FOR OBJECTS
"Article": {
"properties": {
"id": {
"type": "string",
"description": "Unique identifier.”
},
"title": {
"type": "string",
"description": "Title of the article."
},
"text": {
"type": "string",
"description": "Text of the article."
},
"authors": {
"type": "array",
"items": {
"$ref": "#/definitions/Author"
}
…
"Author": {
"properties": {
"id": {
"type":“string”,
“description”:“Unique identifier.”
},
"name": {
"type": "string",
“description”:“Name of the author.”
},
"email": {
"type": "string",,
“description”:“Author’s email.”
}
…
Because we want to return collections of such
objects, we need to define them in Swagger too!!!
Articles and Authors
SWAGGER DEFINITION FOR PATHS
"/articles": {
"get": {
"summary": "Get Articles”,
“operationId”:“getArticles”,
"parameters": {
"name": "size",
"in": "query",
"required": false,
"default": 10,
"maximum": 100,
"type": "number",
"format": "int32"
},
{
"name": "offset",
"in": "query",
"required": false,
"default": 1,
"type": "number",
"format": "int32"
}],
"tags": [ "Articles" ],
"responses": {
"200": {
"description": "An array of
articles",
"schema": {
"$ref": "#/definitions/Articles"
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
}
}
SWAGGER DEFINITION FOR PATHS
"/article/{id}/authors": {
"get": {
"summary": "Get Authors”,
"operationId": "getAuthorByArticleID",
"description": "The Authors endpoint
returns all authors for the specific article
identified by {id}”,
"parameters": [
{
"name": "id",
"in": "path",
"description": "Id of the Article",
"required": true,
"type": "string"
}
],
"tags": [
“Articles”,
"Authors"
],
"responses": {
"200": {
"description": "An array of authors",
"schema": {
"$ref": "#/definitions/Authors"
}
},
"404": {
"description": "Article Not Found",
"schema": {
"$ref": "#/definitions/Error"
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Error"
}
}
…
YAML http://pastebin.com/B2drjPKt
JSON http://pastebin.com/R0EsGyaK
FULL SWAGGER DEFINITION
Try It here: http://editor.swagger.io/
STANDALONE DOCUMENTATION
WITH SWAGGER UI
https://github.com/swagger-api/swagger-ui
SWAGGER-UI
• a part of the Swagger project
• a dependency-free collection of HTML, JS and CSS assets that
dynamically generate documentation
• can host in any server environment
• easy to install and configure
• customizable and supports easy localization and translation
• supports invocation of all HTTP methods (GET, PUT, POST,
DELETE, PATCH, OPTIONS)
SWAGGER UI SETUP
• Make swagger.json and all external $ref accessible via internet
• Setup CORS settings and (optionally) api_key to access them
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, DELETE, PUT,
PATCH, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, api_key,Authorization';
• Download Swagger UI to the server e.g. as swagger-ui
• Make swagger-ui/dist folder accessible via browser (e.g.
configure webserver)
• Just run open it in the browser
DOCUMENTATION EXAMPLE
TESTING API
WITH PYSWAGGER
https://github.com/mission-liao/pyswagger
PYSWAGGER
• a python client for Swagger enabled REST API
• supports Swagger 1.2, 2.0 on python 2.6, 2.7, 3.3, 3.4
• tries hard to fully supports Swagger Spec in all aspects
• supports JSON andYAML
• provides client implementation based on various http
clients in python
• easy to unittest API
• easy to validate API definition according to spec
PYSWAGGER COMPONENTS
PYSWAGGER EXAMPLE
from pyswagger import SwaggerApp, SwaggerSecurity
from pyswagger.contrib.client.requests import Client
# create application from the Swagger spec
app = SwaggerApp._create_(‘https://example.com/swagger.json’)
# specify authorization credentials
auth = SwaggerSecurity(app)
auth.update_with('api_key', '12312312312312312313q')
# create client to access API
client = Client(auth)
# access an Operation object via SwaggerApp.op when operationId is defined
authors = client.request(app.op['getAuthorsByArticleID'](id=1)).data
assert len(authors.items) == authors.total
articles = client.request(app.op[‘getArticles’]).data
assert len(articles.items) <= articles.total
Thank you
@gakhov
Slideshare: www.slideshare.net/gakhov
LinkedIn: www.linkedin.com/in/gakhov

Mais conteúdo relacionado

Mais procurados

Api gateway in microservices
Api gateway in microservicesApi gateway in microservices
Api gateway in microservices
Kunal Hire
 

Mais procurados (20)

Swagger - make your API accessible
Swagger - make your API accessibleSwagger - make your API accessible
Swagger - make your API accessible
 
Consuming Restful APIs using Swagger v2.0
Consuming Restful APIs using Swagger v2.0Consuming Restful APIs using Swagger v2.0
Consuming Restful APIs using Swagger v2.0
 
Designing APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecDesigning APIs with OpenAPI Spec
Designing APIs with OpenAPI Spec
 
Swagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfSwagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdf
 
OpenAPI at Scale
OpenAPI at ScaleOpenAPI at Scale
OpenAPI at Scale
 
Rest API with Swagger and NodeJS
Rest API with Swagger and NodeJSRest API with Swagger and NodeJS
Rest API with Swagger and NodeJS
 
Api gateway in microservices
Api gateway in microservicesApi gateway in microservices
Api gateway in microservices
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Writing REST APIs with OpenAPI and Swagger Ada
Writing REST APIs with OpenAPI and Swagger AdaWriting REST APIs with OpenAPI and Swagger Ada
Writing REST APIs with OpenAPI and Swagger Ada
 
API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0API Docs with OpenAPI 3.0
API Docs with OpenAPI 3.0
 
Angular 4 and TypeScript
Angular 4 and TypeScriptAngular 4 and TypeScript
Angular 4 and TypeScript
 
Nest.js Introduction
Nest.js IntroductionNest.js Introduction
Nest.js Introduction
 
Introduction to GraphQL
Introduction to GraphQLIntroduction to GraphQL
Introduction to GraphQL
 
Postman: An Introduction for Developers
Postman: An Introduction for DevelopersPostman: An Introduction for Developers
Postman: An Introduction for Developers
 
NestJS
NestJSNestJS
NestJS
 
Api testing
Api testingApi testing
Api testing
 
Vue.js
Vue.jsVue.js
Vue.js
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Clean architectures with fast api pycones
Clean architectures with fast api   pyconesClean architectures with fast api   pycones
Clean architectures with fast api pycones
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 

Semelhante a Swagger / Quick Start Guide

MesosCon - Be a microservices hero
MesosCon - Be a microservices heroMesosCon - Be a microservices hero
MesosCon - Be a microservices hero
Dragos Dascalita Haut
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scala
takezoe
 
Benefits of an Open environment with Wakanda
Benefits of an Open environment with WakandaBenefits of an Open environment with Wakanda
Benefits of an Open environment with Wakanda
Alexandre Morgaut
 

Semelhante a Swagger / Quick Start Guide (20)

Building a REST API Microservice for the DevNet API Scavenger Hunt
Building a REST API Microservice for the DevNet API Scavenger HuntBuilding a REST API Microservice for the DevNet API Scavenger Hunt
Building a REST API Microservice for the DevNet API Scavenger Hunt
 
Open API Specifications - formerly swagger
Open API Specifications - formerly swaggerOpen API Specifications - formerly swagger
Open API Specifications - formerly swagger
 
MesosCon - Be a microservices hero
MesosCon - Be a microservices heroMesosCon - Be a microservices hero
MesosCon - Be a microservices hero
 
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016How to generate a REST CXF3 application from Swagger ApacheConEU 2016
How to generate a REST CXF3 application from Swagger ApacheConEU 2016
 
How to Contribute to Apache Usergrid
How to Contribute to Apache UsergridHow to Contribute to Apache Usergrid
How to Contribute to Apache Usergrid
 
Jcon 2017 How to use Swagger to develop REST applications
Jcon 2017 How to use Swagger to develop REST applicationsJcon 2017 How to use Swagger to develop REST applications
Jcon 2017 How to use Swagger to develop REST applications
 
API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)API workshop: Introduction to APIs (TC Camp)
API workshop: Introduction to APIs (TC Camp)
 
Deploy and Access WebSphere Liberty and StrongLoop REST Endpoints on IBM Bluemix
Deploy and Access WebSphere Liberty and StrongLoop REST Endpoints on IBM BluemixDeploy and Access WebSphere Liberty and StrongLoop REST Endpoints on IBM Bluemix
Deploy and Access WebSphere Liberty and StrongLoop REST Endpoints on IBM Bluemix
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scala
 
API Description Languages: Which Is The Right One For Me?
 API Description Languages: Which Is The Right One For Me?  API Description Languages: Which Is The Right One For Me?
API Description Languages: Which Is The Right One For Me?
 
Microservices on Application Container Cloud Service
Microservices on Application Container Cloud ServiceMicroservices on Application Container Cloud Service
Microservices on Application Container Cloud Service
 
Test-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) serviceTest-Driven Documentation for your REST(ful) service
Test-Driven Documentation for your REST(ful) service
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014
 
Building APIs with NodeJS on Microsoft Azure Websites - Redmond
Building APIs with NodeJS on Microsoft Azure Websites - RedmondBuilding APIs with NodeJS on Microsoft Azure Websites - Redmond
Building APIs with NodeJS on Microsoft Azure Websites - Redmond
 
Project onion with swagger
Project onion with swaggerProject onion with swagger
Project onion with swagger
 
Benefits of an Open environment with Wakanda
Benefits of an Open environment with WakandaBenefits of an Open environment with Wakanda
Benefits of an Open environment with Wakanda
 
How to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hoursHow to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hours
 
How to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hoursHow to build a Whatsapp clone in 2 hours
How to build a Whatsapp clone in 2 hours
 

Mais de Andrii Gakhov

Mais de Andrii Gakhov (20)

Let's start GraphQL: structure, behavior, and architecture
Let's start GraphQL: structure, behavior, and architectureLet's start GraphQL: structure, behavior, and architecture
Let's start GraphQL: structure, behavior, and architecture
 
Exceeding Classical: Probabilistic Data Structures in Data Intensive Applicat...
Exceeding Classical: Probabilistic Data Structures in Data Intensive Applicat...Exceeding Classical: Probabilistic Data Structures in Data Intensive Applicat...
Exceeding Classical: Probabilistic Data Structures in Data Intensive Applicat...
 
Too Much Data? - Just Sample, Just Hash, ...
Too Much Data? - Just Sample, Just Hash, ...Too Much Data? - Just Sample, Just Hash, ...
Too Much Data? - Just Sample, Just Hash, ...
 
DNS Delegation
DNS DelegationDNS Delegation
DNS Delegation
 
Implementing a Fileserver with Nginx and Lua
Implementing a Fileserver with Nginx and LuaImplementing a Fileserver with Nginx and Lua
Implementing a Fileserver with Nginx and Lua
 
Pecha Kucha: Ukrainian Food Traditions
Pecha Kucha: Ukrainian Food TraditionsPecha Kucha: Ukrainian Food Traditions
Pecha Kucha: Ukrainian Food Traditions
 
Probabilistic data structures. Part 4. Similarity
Probabilistic data structures. Part 4. SimilarityProbabilistic data structures. Part 4. Similarity
Probabilistic data structures. Part 4. Similarity
 
Probabilistic data structures. Part 3. Frequency
Probabilistic data structures. Part 3. FrequencyProbabilistic data structures. Part 3. Frequency
Probabilistic data structures. Part 3. Frequency
 
Probabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. CardinalityProbabilistic data structures. Part 2. Cardinality
Probabilistic data structures. Part 2. Cardinality
 
Вероятностные структуры данных
Вероятностные структуры данныхВероятностные структуры данных
Вероятностные структуры данных
 
Recurrent Neural Networks. Part 1: Theory
Recurrent Neural Networks. Part 1: TheoryRecurrent Neural Networks. Part 1: Theory
Recurrent Neural Networks. Part 1: Theory
 
Apache Big Data Europe 2015: Selected Talks
Apache Big Data Europe 2015: Selected TalksApache Big Data Europe 2015: Selected Talks
Apache Big Data Europe 2015: Selected Talks
 
API Days Berlin highlights
API Days Berlin highlightsAPI Days Berlin highlights
API Days Berlin highlights
 
ELK - What's new and showcases
ELK - What's new and showcasesELK - What's new and showcases
ELK - What's new and showcases
 
Apache Spark Overview @ ferret
Apache Spark Overview @ ferretApache Spark Overview @ ferret
Apache Spark Overview @ ferret
 
Data Mining - lecture 8 - 2014
Data Mining - lecture 8 - 2014Data Mining - lecture 8 - 2014
Data Mining - lecture 8 - 2014
 
Data Mining - lecture 7 - 2014
Data Mining - lecture 7 - 2014Data Mining - lecture 7 - 2014
Data Mining - lecture 7 - 2014
 
Data Mining - lecture 6 - 2014
Data Mining - lecture 6 - 2014Data Mining - lecture 6 - 2014
Data Mining - lecture 6 - 2014
 
Data Mining - lecture 5 - 2014
Data Mining - lecture 5 - 2014Data Mining - lecture 5 - 2014
Data Mining - lecture 5 - 2014
 
Data Mining - lecture 4 - 2014
Data Mining - lecture 4 - 2014Data Mining - lecture 4 - 2014
Data Mining - lecture 4 - 2014
 

Último

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Último (20)

MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Swagger / Quick Start Guide

  • 1. SWAGGER 2.0 Quick Start Guide tech talk @ ferret Andrii Gakhov
  • 2. WHAT IS 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, or through network traffic inspection. • Swagger is a formal specification surrounded by a large ecosystem of tools
  • 3. SWAGGER ECOSYSTEM • Swagger Editor
 edit API specifications inYAML inside browser and preview documentations in real time. • Swagger Codegen
 allows generation of both client libraries and server stubs from a Swagger definition. • Swagger UI
 dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger- compliant API http://swagger.io/tools/
  • 4. USAGE PATTERNS FOR API PROVIDERS Swagger Editor Swagger Definition Swagger Codegen Swagger UI API Swagger Editor Swagger Definition Swagger Codegen Swagger UI API API Swagger-Core JAX-RS Automatic generation top-down approach bottom-up approach
  • 5. SWAGGER SPECIFICATION • The Swagger representation of the API is made of a single file swagger.json (but can refer to other resources) • Represented as JSON, butYAML can be used • All field names are case sensitive • Primitive data types in the Swagger Specification are based on the types supported by the JSON-Schema Draft 4. • Models are described using the Schema Object which is a subset of JSON Schema Draft 4. https://github.com/swagger-api/swagger-spec/
  • 6. SWAGGER OBJECT info API metadata paths available paths and operations definitions data types produced and consumed by operations parameters parameters that can be used across operations responses responses that can be used across operations securityDefinitions security scheme definitions security alternative security schemes that can be used tags list of tags with additional metadata externalDocs additional external documentation
  • 10. COMMUNITY-DRIVEN LANGUAGE INTEGRATIONS • Clojure • ColdFusion / CFML • Eiffel • Go • Groovy • Java • JavaScript • Node.js • Perl • PHP • Python • Ruby • Scala https://github.com/swagger-api/swagger-spec#additional-libraries
  • 12. UNFORMAL SPECIFICATION • We want to design DEMO API that can provide access to our database of articles • Every article in the database has a list of authors, so internally we have 2 main data objects:Article and Author • All responses from our API should be made in JSON • We want to able: 1. get all articles
 GET /v1/articles 2. get all authors from the particular article
 GET /v1/article/{id}/authors
  • 13. SWAGGER DEFINITION METADATA "swagger": "2.0", "info": { "title": "DEMO API", "description": "Demonstration for techtalk @ ferret", "version": "1.0.0" }, "host": "api.demo.berlin", "schemes": [ "http", "https" ], "basePath":“/v1", “consumes”: [ “application/json” ], "produces": [ "application/json" ],
  • 14. SWAGGER DEFINITION FOR OBJECTS "Article": { "properties": { "id": { "type": "string", "description": "Unique identifier.” }, "title": { "type": "string", "description": "Title of the article." }, "text": { "type": "string", "description": "Text of the article." }, "authors": { "type": "array", "items": { "$ref": "#/definitions/Author" } … "Author": { "properties": { "id": { "type":“string”, “description”:“Unique identifier.” }, "name": { "type": "string", “description”:“Name of the author.” }, "email": { "type": "string",, “description”:“Author’s email.” } … Because we want to return collections of such objects, we need to define them in Swagger too!!! Articles and Authors
  • 15. SWAGGER DEFINITION FOR PATHS "/articles": { "get": { "summary": "Get Articles”, “operationId”:“getArticles”, "parameters": { "name": "size", "in": "query", "required": false, "default": 10, "maximum": 100, "type": "number", "format": "int32" }, { "name": "offset", "in": "query", "required": false, "default": 1, "type": "number", "format": "int32" }], "tags": [ "Articles" ], "responses": { "200": { "description": "An array of articles", "schema": { "$ref": "#/definitions/Articles" } }, "default": { "description": "Unexpected error", "schema": { "$ref": "#/definitions/Error" } } } }
  • 16. SWAGGER DEFINITION FOR PATHS "/article/{id}/authors": { "get": { "summary": "Get Authors”, "operationId": "getAuthorByArticleID", "description": "The Authors endpoint returns all authors for the specific article identified by {id}”, "parameters": [ { "name": "id", "in": "path", "description": "Id of the Article", "required": true, "type": "string" } ], "tags": [ “Articles”, "Authors" ], "responses": { "200": { "description": "An array of authors", "schema": { "$ref": "#/definitions/Authors" } }, "404": { "description": "Article Not Found", "schema": { "$ref": "#/definitions/Error" } }, "default": { "description": "Unexpected error", "schema": { "$ref": "#/definitions/Error" } } …
  • 17. YAML http://pastebin.com/B2drjPKt JSON http://pastebin.com/R0EsGyaK FULL SWAGGER DEFINITION Try It here: http://editor.swagger.io/
  • 18. STANDALONE DOCUMENTATION WITH SWAGGER UI https://github.com/swagger-api/swagger-ui
  • 19. SWAGGER-UI • a part of the Swagger project • a dependency-free collection of HTML, JS and CSS assets that dynamically generate documentation • can host in any server environment • easy to install and configure • customizable and supports easy localization and translation • supports invocation of all HTTP methods (GET, PUT, POST, DELETE, PATCH, OPTIONS)
  • 20. SWAGGER UI SETUP • Make swagger.json and all external $ref accessible via internet • Setup CORS settings and (optionally) api_key to access them add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, DELETE, PUT, PATCH, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type, api_key,Authorization'; • Download Swagger UI to the server e.g. as swagger-ui • Make swagger-ui/dist folder accessible via browser (e.g. configure webserver) • Just run open it in the browser
  • 23. PYSWAGGER • a python client for Swagger enabled REST API • supports Swagger 1.2, 2.0 on python 2.6, 2.7, 3.3, 3.4 • tries hard to fully supports Swagger Spec in all aspects • supports JSON andYAML • provides client implementation based on various http clients in python • easy to unittest API • easy to validate API definition according to spec
  • 25. PYSWAGGER EXAMPLE from pyswagger import SwaggerApp, SwaggerSecurity from pyswagger.contrib.client.requests import Client # create application from the Swagger spec app = SwaggerApp._create_(‘https://example.com/swagger.json’) # specify authorization credentials auth = SwaggerSecurity(app) auth.update_with('api_key', '12312312312312312313q') # create client to access API client = Client(auth) # access an Operation object via SwaggerApp.op when operationId is defined authors = client.request(app.op['getAuthorsByArticleID'](id=1)).data assert len(authors.items) == authors.total articles = client.request(app.op[‘getArticles’]).data assert len(articles.items) <= articles.total