Skip to content

Instantly share code, notes, and snippets.

@eriknguyen
Last active January 22, 2018 08:39
Show Gist options
  • Save eriknguyen/c191a7d1493723bf808191193e3db4e3 to your computer and use it in GitHub Desktop.
Save eriknguyen/c191a7d1493723bf808191193e3db4e3 to your computer and use it in GitHub Desktop.
Overview on building web API with Flask

Building Web APIs with Flask

Following the same-name course on Lynda.com

1. Getting up to speed with Flask

  • Use of __var_name and self.var_name in model
  • Decorator for oop in Python: @var_name.setter...
  • User serialize() for convert a class instance to dictionary type
  • Use app.error_handler_spec dictionary to map error handler to different handler

2. Create and Read

2.a. Create

  • Create operation -> POST
  • Meaningful HTTP Response code:
    • 201 Created,
    • 500 Internal Server Error,
    • 400 Bad Request
  • If success -> response should contain access path for new entity
  • Always authenticate

2.b. Read

  • Use parameter serialize = True/False to get entity in different format

3. Update and Delete

3.a. Update

  • Use PUT
  • 2 approaches:
    • Can create data if not existed -> if new entity, return code 201 Created
    • NOT create data -> return that there's nothing to update
  • Response code:
    • 404 Not Found
    • 200 OK: for success, response contains entity
    • 204 No Content: for success, response NOT contains entity

3.b. Delete

  • Use DELETE
  • Response code:
    • 404 Not Found
    • 204 No Content : for a successful delete
    • Optional: 200 OK - for a successful delete but with the deleted entity in response body

3.c. Hypermedia & HATEOAS

  • Using JSON LD

4. Extending the Web API

4.a. Authentication

  • Different mechanisms:
    • Basic HTTP authentication:
      • Use pair of username/password
      • Request headers with contain: Authorization header with content is Basic {base65_encoded_user_password}
      • Can implement using a wrapper decorator
    • Cookies
    • Hash message based authentication
    • OAuth
  • Should always use SSL/HTTPS

4.b. HTTP Caching

  • What is caching
    • Component that stores data -> future requests for the data can be served faster
  • Types of caching
    • HTTP Header caches with ETag
      • ETag header store cache info eg. the time that request was responded
      • Use with Cache-Control header too
    • Application Level cache (eg. Redis, Hazel Cache)
    • Gateway or Reverse Proxy cache
  • Use eTags for cache control
    • ETag = entity tag, based on resourced hashed and timestamp
  • Code for setting ETag

4.c. Error Handling in RESTful APIs

  • HTTP error codes
    • Common codes: 200, 400, 401, 403, 404, 405, 500, 501
  • Application Specific Error Codes in HTTP Headers
    • Custom headers should start with X-HEADER_NAME
    • Code: X-MyAPI-Error-Code: 15
    • Message: X-MyAPI-Error-Message: "error message here"
  • Meaningful error messages in HTTP Headers

4.d. Guidelines for Building Large Projects

  • Modular architecture
    • App is built up using small parts
    • Modules connect to each other through well defined interfaces
    • Modules can be reused in different projects
  • REST API architecture guideline
    • Define interface -> human readable, meaningful routes, easy to remember
    • Apply standards for HTTP Response codes
    • Version the API
    • Follow KISS principle (Keep It Simple, Stupid)
    • Design for supporting:
      • CRUD operations
      • Authorization
      • Permissions
      • Caching
  • Flask Blueprints
    • What?
      • Application component within Flask
      • Have access to app config
      • Can change app config when registered
    • Why?
      • Help to build up large apps
      • Can be registered for subdomains or URLs
      • Different Blueprints can be created for different versions

5. Securing Web APIs

5.a. Why HTTPS?

  • HTTPS use TLS or SSL
  • Ensures secure communication transport
  • Messages sent from client to server are encrypted
  • Protects from:
    • Man in the middle attacks
    • Eavesdroppers (unwanted listeners of the communicating channel)

5.b. Token Authentication

  • Token
    • Stateless -> should be sent with each request
    • Usually set in HTTP header
  • Flask-security can be used
  • Implement token-based authentication

5.c. Cookies

  • Sent between browser and server
  • Common types:
    • Secure Cookie
    • HTTP Only Cookie
    • Session Cookie
    • Persistent Cookie

5.d. Storing Passwords

  • Always store as some form of hash code
  • User credentials should be held in a separate database on different server
  • If needed, an authentication microservice can be implemented for authentiation

6. Testing Web APIs

6.1. Using the Flask Test Client

  • Flask test client - from the Werkzeug framework
  • Works with unittest module

6.2. Testing Custom Flask Routes

6.3. Testing CRUD

6.4. Testing Authentication

  • Test authorization success + fail

REST Best Practices

  • Always apply versioning for your API
  • Always use meaningful HTTP Response Codes (200 OK, 404 Not Found, 401 Unauthorized, 201 Created, etc.)
  • Secure data with authentication
  • Use caching if needed

Other Notes

  • PUT vs PATCH:
    • Both for update
    • PUT first try to update the data item, if it's not existed, it will try to save the item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment