How To Build A REST API With Flask
How To Build A REST API With Flask
This guide will walk you through creating a basic REST API using Flask, a popular
Python web framework, along with SQLAlchemy for database interaction.
### Prerequisites
---
```bash
mkdir flask_api_project
cd flask_api_project
```
```bash
python3 -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
```
---
Install Flask, Flask-SQLAlchemy (for database ORM), and Flask-RESTful (for easy
REST API creation).
```bash
pip install Flask Flask-SQLAlchemy Flask-RESTful
```
---
```python
# app.py
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
```
---
```python
from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
```
---
```python
# app.py
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
age = db.Column(db.Integer, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f"User(name={self.name}, age={self.age}, email={self.email})"
```
```bash
python
>>> from app import db
>>> db.create_all()
>>> exit()
```
---
Define endpoints for CRUD operations. Each endpoint will correspond to a class
inheriting from `flask_restful.Resource`.
```python
# app.py
from flask import request
from flask_restful import Resource
class UserResource(Resource):
def get(self, user_id):
user = User.query.get_or_404(user_id)
return {"id": user.id, "name": user.name, "age": user.age, "email":
user.email}, 200
def post(self):
data = request.get_json()
new_user = User(name=data['name'], age=data['age'], email=data['email'])
db.session.add(new_user)
db.session.commit()
return {"message": "User created successfully"}, 201
---
Add the following code to register the `UserResource` with the API.
```python
# app.py
api.add_resource(UserResource, '/user/<int:user_id>', '/user')
```
---
Add the following code to the bottom of `app.py` to run the Flask application.
```python
# app.py
if __name__ == '__main__':
app.run(debug=True)
```
```bash
python app.py
```
---
```bash
curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "age":
30, "email": "john@example.com"}' http://127.0.0.1:5000/user
```
```bash
curl http://127.0.0.1:5000/user/1
```
```bash
curl -X PUT -H "Content-Type: application/json" -d '{"name": "John Doe", "age":
31, "email": "john_doe@example.com"}' http://127.0.0.1:5000/user/1
```
```bash
curl -X DELETE http://127.0.0.1:5000/user/1
```
---
### Conclusion
You’ve successfully built a REST API with Flask! This API can serve as a foundation
for more complex applications, or be extended with additional endpoints and
features.
---