python-backend
/

Building REST APIs with Flask

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Building REST APIs with Flask

What is Flask?

Flask is a 'micro' web framework for Python. It is called micro because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. This makes it incredibly flexible and an excellent choice for building lightweight REST APIs or microservices.

Setting Up a Simple Flask API

To create an API endpoint in Flask, you define a function and decorate it with @app.route(). You specify the URL path and the allowed HTTP methods.

PythonRead-only
1
from flask import Flask, jsonify, request

app = Flask(__name__)

# A simple in-memory data store
items = [{"id": 1, "name": "Item One"}]

@app.route('/items', methods=['GET'])
def get_items():
    return jsonify(items)

if __name__ == '__main__':
    app.run(debug=True)

Handling POST Requests

When building a REST API, you often need to receive data from the client. In Flask, you use the request object to access the JSON payload sent in the body of a POST request.

PythonRead-only
1
@app.route('/items', methods=['POST'])
def add_item():
    new_item = request.get_json()
    items.append(new_item)
    return jsonify(new_item), 201

Dynamic Routing (URL Parameters)

You can capture values from the URL using angle brackets <>. This is essential for building endpoints that act on specific resources, like fetching a single user by their ID.

PythonRead-only
1
@app.route('/items/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = next((i for i in items if i['id'] == item_id), None)
    if item:
        return jsonify(item)
    return jsonify({"error": "Item not found"}), 404

Flask vs. FastAPI for REST

FeatureFlaskFastAPI
StyleWSGI (Synchronous)ASGI (Asynchronous)
Data ValidationManualAutomatic (via Pydantic)
SpeedFastVery Fast
DocumentationRequires extensionsAutomatic Swagger UI
FlexibilityExtremely HighHigh (but opinionated)

Test Your Knowledge

Q1
of 3

Which decorator is used to define a route in Flask?

A
@app.path()
B
@app.route()
C
@flask.api()
D
@route.add()
Q2
of 3

Which Flask object is used to access incoming request data like JSON or form values?

A
response
B
payload
C
request
D
data
Q3
of 3

What is the purpose of the 'debug=True' flag in app.run()?

A
It makes the API faster
B
It enables a debugger and automatically reloads the server on code changes
C
It hides errors from the user
D
It prepares the app for production deployment

Frequently Asked Questions

What is 'jsonify' in Flask?

It is a helper function that turns a Python dictionary or list into a JSON response object and automatically sets the 'Content-Type' header to 'application/json'.

How do I handle CORS in Flask?

If your Flutter or React app is on a different domain, you'll need the 'Flask-CORS' extension to allow the browser to make requests to your API.

Is Flask suitable for production?

Yes! While the built-in server is for development only, Flask apps are production-ready when deployed behind a robust WSGI server like Gunicorn or uWSGI.

Previous

flask request response

Next

django introduction

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.