Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Cómo construir un API del que tus padres se sientan orgullosos

Cómo construir un API del que tus padres se sientan orgullosos

Necesitas construir una API, ¿pero conoces qué herramientas deberías usar? Cada día aparecen nuevas herramientas pensadas para crear, testear y desplegar APIs. En esta charla se presentará de manera resumida un caso real: el proceso de construcción de una API usando Python desde su diseño hasta su puesta en producción. Veremos los problemas encontrados por nuestro equipo y obviamente sus soluciones.

Adrián Matellanes

October 08, 2016
Tweet

More Decks by Adrián Matellanes

Other Decks in Programming

Transcript

  1. About Me GET /speakers/adrian-matellanes { "name": "Adrián Matellanes", "roles": [

    "Lead API Developer", "Málaga Python Organizer" ], "worksAt": "Ebury" "twitter": "@_amatellanes", "github": "github.com/amatellanes" }
  2. What is a RESTful API? Constraints • Client-Server • Stateless

    • Cacheable • Layered System • Uniform Interface
  3. What is a RESTful API? Uniform Interface • Identification of

    resources • Manipulation of resources through representations • Self Descriptive Messages • Hypermedia As The Engine Of Application State (HATEOAS)
  4. RMM (Richardson Maturity Model) Level 1: Resources • GET -

    /api/characters • GET - /api/characters/583 • GET - /api/characters/211
  5. RMM (Richardson Maturity Model) Level 2: HTTP Verbs • GET

    • POST • DELETE • PUT • PATCH • OPTIONS • HEAD
  6. RMM (Richardson Maturity Model) Level 2: HTTP Verbs • POST

    - /api/characters • GET - /api/characters • GET|PUT|DELETE - /api/characters/823
  7. RMM (Richardson Maturity Model) Level 3: Hypermedia controls GET /api/houses/362

    { "name": "House Stark of Winterfell", "region": "The North", "words": "Winter is Coming", "founder": "/api/characters/209", }
  8. RMM (Richardson Maturity Model) Level 3: Hypermedia controls HAL http://stateless.co/hal_specification.html

    JSON-LD http://json-ld.org/ Collection+JSON http://amundsen.com/media-types/collection/ JSON Schema http://json-schema.org/
  9. HTTP Status Code 2xx Success • 200 - OK •

    201 - Created • 204 - No Content
  10. HTTP Status Code 4xx Client Error • 400 - Bad

    Request • 401 - Unauthorized • 403 - Forbidden • 404 - Not Found • 405 - Method Not Allowed
  11. HTTP Status Code 5xx Server Error • 500 - Internal

    Server Error • 501 - Not Implemented • 502 - Bad Gateway • 503 - Service Unavailable
  12. API

  13. API Specification Swagger swagger: '2.0' info: version: '1.0.0' title: Game

    of Thrones API Description: All the data from the universe of Ice And Fire you've ever wanted schemes: - https basePath: /v1 produces: - application/json securityDefinitions: OauthSecurity: type: oauth2 flow: accessCode authorizationUrl: 'https://oauth.simple.api/authorization' tokenUrl: 'https://oauth.simple.api/token' ...
  14. API Specification Swagger … paths: /characters/{id}: get: summary: Get specific

    character parameters: - name: id in: path description: The identifier of this character required: true type: string responses: 200: description: History information for the given character schema: $ref: '#/definitions/Character' ...
  15. API Specification Swagger … definitions: Character: type: object properties: name:

    type: string description: The name of this character gender: type: string description: The gender of this character example: name: Oberyn Martell gender: Male
  16. API Specification RAML 506 results 834 repositories 2,329 stars 98,000

    results https://github.com/raml-org/raml-spec
  17. API Specification RAML #%RAML 1.0 title: Game of Thrones API

    version: v1 baseUri: http://{hostName}.com baseUriParameters: hostName: description: The name of the host mediaType: application/json documentation: - title: Game of Thrones API Documentation content: All the data from the universe of Ice And Fire you've ever wanted securitySchemes: oauth_2_0: !include securitySchemes/oauth_2_0.raml ...
  18. API Specification RAML … /characters: /{id}: uriParameters: id: type: number

    description: The identifier of this character get: description: | Get specific character responses: 200: body: application/json: schema: !include schemas/character.json example: !include examples/character.json
  19. API Specification RAML # schemas/character.json { "type": "object", "$schema": "http://json-schema.org/draft-03/schema",

    "required": true, "properties": { "name": { "type": "string", "required": true, "maxLength": 125 }, "gender": { "type": "string" } } }
  20. API Specification API Blueprint 943 results 409 repositories 4,325 stars

    404,000 results https://github.com/apiaryio/api-blueprint
  21. API Specification API Blueprint FORMAT: 1A HOST: http://got.api.com/ # Game

    of Thrones API All the data from the universe of Ice And Fire you've ever wanted. ...
  22. API Specification API Blueprint ... # Group Characters ## Character

    Resource [/characters/{id}] + Parameters + id: 422 (number) - The identifier of this character ### Get specific character [GET] + Response 200 (application/json) + Attributes - characters (Character) ...
  23. API Specification API Blueprint ... # Data Structures ## Character

    (object) - name: Oberyn Martell (required, string) - The name of this character - gender: Male (required, string) - The gender of this character
  24. API Development What I DO want • Python 3 Support

    • HTTP request/response • Easy to understand and use (documentation, minimal magic, no surprise) • Packages • URL Routing (RESTful) • WSGI
  25. API Development Awesome Python webargs - Parse HTTP request arguments

    https://github.com/sloria/webargs marshmallow - Simplified object serialization https://github.com/marshmallow-code/marshmallow Requests - HTTP for Humans https://github.com/kennethreitz/requests
  26. API Development Awesome Flask Flask-RESTful - Quick building REST APIs

    https://github.com/flask-restful/flask-restful Flask API - Browsable Web API https://github.com/tomchristie/flask-api Connexion - Automagically handles HTTP requests based on Swagger Spec https://github.com/zalando/connexion
  27. API Development Flask-RESTful Example from flask import Flask from flask_restful

    import Resource, Api app = Flask(__name__) api = Api(app) ...
  28. API Development Flask-RESTful Example ... class Character(Resource): def get(self, id):

    return { 'name': 'Oberyn Martell', 'culture': 'Dornish' } api.add_resource(Character, '/characters/<string:id>') ...
  29. API Testing HTTPretty Example @httpretty.activate def test_got_api_returning_deals(): httpretty.register_uri(httpretty.GET, 'http://api.got.com/v1/characters/583', body='{'name':

    'Jon Snow'}', content_type='application/json') response = requests.get('http://api.got.com/v1/characters/583') expect(response.json()).to.equal({'name': 'Jon Snow'})
  30. Integration Testing Dredd A language-agnostic command-line tool for validating API

    description document against backend implementation of the API. https://github.com/apiaryio/dredd
  31. Integration Testing Wiremock Mock your APIs for fast, robust and

    comprehensive testing https://github.com/tomakehurst/wiremock
  32. Integration Testing Wiremock stub example { "request": { "method": "GET",

    "url": "/v1/characters/583" }, "response": { "status": 200, "bodyFileName": "jon-snow.json", "headers": { "Content-Type": "application/json" } } }
  33. API Developer Portal Tips • Document precisely and with examples

    • Authentication • Endpoints • SDKs • Changelog
  34. More... API Design Guides PayPal API Style Guide https://github.com/paypal/api-standards Heroku

    Platform HTTP API Design Guide https://github.com/interagent/http-api-design Microsoft REST API Guidelines https://github.com/Microsoft/api-guidelines
  35. More... API Examples GitHub API v3 https://developer.github.com/v3/ Facebook Graph API

    https://developers.facebook.com/docs/graph-api Twitter REST API https://dev.twitter.com/rest/public Spotify Web API https://developer.spotify.com/web-api/