Start learning free

LESSON 15 OF 188 · BACKEND: YOUR FIRST API

More Routes in Python

Practice

An API has many paths, and each path has its own function. When a request arrives, Flask compares its path with the path of every route, and calls the function whose path matches exactly. So /products/count is not /products: it needs a route of its own.

A route can answer any dictionary as JSON. For example, a shop could tell its opening hours like this:

@app.get("/hours")
def hours():
    return jsonify({"open": 9, "close": 18})

To answer how many items a list has, use len(...) instead of writing the number yourself: the answer stays right when items are added or removed. A path that no route matches, like /contact, gets 404 Not Found: Flask has no function to call.

Your app must answer:

GET /products/count  →  200  {"count": 4}
GET /about           →  200  {"name": "Corner Shop", "currency": "USD"}
GET /contact         →  404  (an HTML error page)
GET /products        →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}, … all 4 products]
GET /                →  200  Welcome to the shop!

Your task: add two routes. GET /products/count, with a function named count_products, answers the number of products as {"count": …}, computed with len(products). GET /about, with a function named about, answers the shop's "name", "Corner Shop", and its "currency", "USD".


Assignment
Follow the Coding Tutorial to add the /products/count and /about routes.


Hint
Each new route has the same shape as the others: the decorator with its path, the def line with a new function name, then the return. Put each dictionary inside jsonify(...).


STEP 1 OF 6
    Ctrl + Enter to check

    Shop More Routes in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free