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

HTTP API & Python

Milan Cermak
February 20, 2013

HTTP API & Python

Slides from my talk at Brno and Prague Python user group meetups on HTTP/REST APIs.

Milan Cermak

February 20, 2013
Tweet

More Decks by Milan Cermak

Other Decks in Programming

Transcript

  1. HTTP API & Py Milan Čermák Pyvo Praha, 20. 2.

    2013 Wednesday, February 20, 13
  2. "While HTTP isn’t always the best answer, it’s a damn

    fine first guess." Coda Hale Wednesday, February 20, 13
  3. Benefits of HTTP The most widespread application protocol Statelessness Optional

    caching Promotes layered infrastructure Wednesday, February 20, 13
  4. Benefits of HTTP The most widespread application protocol Statelessness Optional

    caching Promotes layered infrastructure etc. Wednesday, February 20, 13
  5. import handlers urls = [(r"/user", handlers.users.NewUser), (r"/user/(\d+)", handlers.users.User)] class User(handler.base.BaseHandler):

    def delete(self, user_id): pass def get(self, user_id): pass def post(self, user_id): pass Wednesday, February 20, 13
  6. class UserValidatorMixin(object): def check_user_data(self, user_dict): pass class User(handler.base.BaseHandler, UserValidatorMixin): def

    post(self, user_id): new_user = self.get_argument(“user”) if not self.check_user_data(new_user): return self.http_error(400, “Invalid data”) Wednesday, February 20, 13
  7. import json class AppJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, User):

    return {"name": obj.name, "height": obj.height, "cash": obj.get_bank_account_balance()} return json.JSONEncoder.default(self, obj) user = User("1337") json.dumps(user, cls=AppJSONEncoder) Wednesday, February 20, 13
  8. Compression of HTTP bodies HTTP/1.1 200 OK Content-Encoding: gzip Content-Type:

    application/json; charset=utf-8 Wednesday, February 20, 13
  9. Compression of HTTP bodies POST /user HTTP/1.1 Host: api.napyvo.io Content-Encoding:

    gzip Content-Type: application/json [gzipped representation of a user] Wednesday, February 20, 13
  10. Caching Cache-Control: max-age=3600 Expires: Thu, 31 Jan 2013 22:00:00 GMT

    <- Last-Modified: Thu, 31 Jan 2013 18:30:00 GMT -> If-Modified-Since: Wed, 30 Jan 2013 13:37:00 GMT ETag: foo If-None-Match: foo Wednesday, February 20, 13
  11. GET /car/9?zoom=passengers {"car": { "color": "red", "passengers": [ {"href": "/user/1337",

    "rel": "self", "name": "Milan", "drink": "beer", "skills": ["python", "http"], }] } } Wednesday, February 20, 13