Beautiful REST-APIs




From design to implementation with Swagger



Created by David Dornseifer / @dp_dornseifer

REST-APIs

What do developers expect


  • easy to use
  • documentation
  • playground (browser / curl)

What do I expect


  • people build cool stuff
  • gets famous in the community
  • people recommend to use it

API-Accidents


  • Exposing of operations instead of objects
  • Response has HTML fragments
  • Google API

Gif taken from giphy.com

What is good API-Design

Naming


  • Nouns, non verbs
  • Plural nouns for collections
  • /beers.json/{beerId}

HTTP-Verbs


Method Scope Semantics
GET collection Retrieve all resources in a collection
GET resource Retrieve a single resource
POST collection Create a new resource in a collection
PUT resource Update a resource
DELETE resource Delete a recource

Errors


Code Semantics
200 Success, everything worked
400 App did something wrong, client error
500 API did something wrong, server error


Possible: 201 - Created , 304 - Not Modified, 404 - Not Found, 401 - Unauthorized, 403 - Forbidden

Versioning


  • Keep old versions active for smooth transition
  • API should not change frequently, no /v10.2
  • www.host.com/api/v1/beer

Pagination


  • Use Query-Parameter
  • Have default values in place (?limit=10&offset=10)
  • ?limit=10
  • ?offset=20

Partial Response


  • Use query parameters for fields
  • Have a default list in place (PK)
  • ?fields=beerId,displayName,stock

Formats


  • Support more than one response formats
  • Define it like a filename extension
  • /pets.json
  • /pets.xml
  • /pets.odata

Attributs/Naming conventions


  • Consistent over all APIs
  • sanke_case vs. camelCase

Search


  • '/beer.json?q=ipa' for specific enpoint
  • '/search.json?q=beer' for global domain search

Gif taken from giphy.com

Sources

Swagger

  • OpenSource REST-Spec Framework like RAML, API-Blueprint
  • Strong developer community on GitHub
  • Tool and language support

API-Design with Swagger

  1. Design/model driven approach
  2. Annotate exsisting Rest-APIs

Model driven Approach

  1. Use Swagger Editor to define REST-APIs
  2. Generate server or client stubs with Swagger Codegen
  3. Implement API - Do the magic :)
  4. Use Swagger UI as API-Console

Swagger-Annotations

  • Annotate REST-API source code with Swagger @nnotations
  • Build tool generates swagger.json/.yaml with Swagger Core libraies
  • Use Swagger-UI as API-Console

THE END