Advanced level · Module 4: Building Web APIs with Flask · Lesson 1 of 5
Flask Routes and JSON Responses
Create a Flask application with routes that return JSON data.
In this lesson you will
- Create a Flask app and run the development server
- Return JSON with appropriate status codes
Key concepts
routeHTTP methodjsonifystatus code
The lesson
Flask is a lightweight Python framework for building web applications and APIs. A route connects a URL to a Python function: @app.get('/products') runs a function when that URL is requested.
For an API, the function returns data as JSON — Flask converts dictionaries and lists automatically — together with the right status code: 200 for success, 404 when the item does not exist.
Run the development server with flask run and test your endpoints in a browser or with a tool such as curl.
Step by step
- Install Flask and create app.py.
- Add GET /products returning all products from SQLite.
- Add GET /products/<int:id> returning one product or 404.
- Test both endpoints and check the status codes.
Practice activity
Build GET /products and GET /products/<id> endpoints returning data from your SQLite database, with 404 for unknown ids.
Expected result: Two working endpoints with correct responses and status codes.
Check your understanding
-
Which status code should a successful creation return?
Show answer
201 Created.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.