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.
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.
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.
Flask vs. FastAPI for REST
| Feature | Flask | FastAPI |
|---|---|---|
| Style | WSGI (Synchronous) | ASGI (Asynchronous) |
| Data Validation | Manual | Automatic (via Pydantic) |
| Speed | Fast | Very Fast |
| Documentation | Requires extensions | Automatic Swagger UI |
| Flexibility | Extremely High | High (but opinionated) |