Flask as API (BASIC)

Web Development

Using flask as api

Stack choices

  • Python 3.6 with venv
  • Flask
  • JWT token

Pre-requisite

Familiar with - Python3 - Basic HTTP Request (GET, POST, PUT, DELETE) - Basic SQL

Some Python Lambda reference for JS Developer

Filter

python version:

number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

# Output: [-5, -4, -3, -2, -1]

javascript version:

var number_list = Array.from(Array(10).keys()).map(i => i-5);
var less_than_zero = number_list.filter(i => i<0);
console.log(less_than_zero);
// Output: [-5, -4, -3, -2, -1]

Environment setup

  1. Install flask (pip install flask)
  2. Go to the chosen directory
  3. Create virtualenv
    • Install virtualenv pip install virtualenv
    • Create venvvirtualenv venv --python=python3.6
    • Activate virtualenv

source venv/bin/activate (for mac/linux) ./venv/Scripts/activate.bat (for windows)

Basic Flask app

from flask import Flask # import flask library

app = Flask(__name__) # create flask obj
@app.route('/') # set route to localhost:5000/
def home(): # create home function
  return 'Hello, World!' # return the request to / with "Hello, World!"

app.run(port: 5000) # Start flask web at port 5000

Some HTTP verbs

GET | Retrieve Something | GET /stuff/1

POST | Receive data and use it (with extra data) | POST /stuff {'name': 'test'}

PUT | Similar to POST, but it can use to update | PUT /stuff {'name': 'test'}

DELETE | Destroy something | DELETE /stuff/1


profile image
Written by Lai Weng Han