swagger / quick start guide

Post on 13-Aug-2015

67 Views

Category:

Software

8 Downloads

Preview:

Click to see full reader

TRANSCRIPT

SWAGGER 2.0Quick Start Guide

tech talk @ ferretAndrii 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 in YAML 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

SwaggerEditor

SwaggerDefinition

SwaggerCodegen

SwaggerUI

API

Swagger Editor

SwaggerDefinition

SwaggerCodegen

SwaggerUI

API

APISwagger-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, but YAML 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 OBJECTinfo

API metadatapaths

available paths and operations

definitionsdata types produced and consumed by operations

parametersparameters that can be used across operations

responsesresponses that can be used across operations

securityDefinitionssecurity scheme definitions

securityalternative security schemes that can be used

tagslist of tags with additional metadata

externalDocsadditional 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 articlesGET /v1/articles

2. get all authors from the particular articleGET /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 DOCUMENTATIONWITH 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 APIWITH 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 and YAML

• 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 EXAMPLEfrom 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 APIclient = 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’]).dataassert len(articles.items) <= articles.total

Thank you@gakhov

Slideshare: www.slideshare.net/gakhovLinkedIn: www.linkedin.com/in/gakhov

top related