PythiloLesson 4 of 5 · progress kept in this browser

Flask routes

Flask maps URLs to functions. A route returns a value, and Flask builds the response. Returning a dict or list sends JSON.

from flask import Flask, request

app = Flask(__name__)

@app.get("/users/<int:user_id>")
def user(user_id):
    return {"id": user_id}

@app.post("/users")
def add():
    data = request.get_json(silent=True)
    return {"ok": True}, 201
  • A route may return (body, status).
  • <int:x> only matches digits and passes an int, so other text gets a 404.
  • abort(404) stops with that status.
  • get_json(silent=True) returns None rather than an error for a body that is not JSON.
Your task

Finish create_app(). POST /items with JSON {"name": "tea"} stores an item with the next id from 1 and returns it with status 201. A body with no non-empty name, or a body that is not JSON, returns status 400 with {"error": ...}. GET /items/<int:item_id> returns the item or a 404.

This lesson uses Flask, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.