# 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
- Basic knowledge of Python
- Python 3.x installed on your machine
- `pip` for installing Python packages
---
### Step 1: Set Up Your Environment
Create a directory for your project and navigate into it.
```bash
mkdir flask_api_project
cd flask_api_project
```
Create a virtual environment for package management.
```bash
python3 -m venv venv
source venv/bin/activate # On Windows, use `venv\Scripts\activate`
```
---
### Step 2: Install Required Packages
Install Flask, Flask-SQLAlchemy (for database ORM), and Flask-RESTful (for easy
REST API creation).
```bash
pip install Flask Flask-SQLAlchemy Flask-RESTful
```
---
### Step 3: Initialize the Flask Application
Create a file named `[Link]` and set up a basic Flask application.
```python
# [Link]
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
```
---
### Step 4: Configure the Database
For this guide, we’ll use SQLite for simplicity, but this can be swapped out for
PostgreSQL or another database. Add the following to `[Link]` to set up the
database.
```python
from flask_sqlalchemy import SQLAlchemy
[Link]['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///[Link]'
[Link]['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
```
---
### Step 5: Define a Data Model
Create a `User` model for storing users in the database.
```python
# [Link]
class User([Link]):
id = [Link]([Link], primary_key=True)
name = [Link]([Link](80), nullable=False)
age = [Link]([Link], nullable=False)
email = [Link]([Link](120), unique=True, nullable=False)
def __repr__(self):
return f"User(name={[Link]}, age={[Link]}, email={[Link]})"
```
To create the database, run:
```bash
python
>>> from app import db
>>> db.create_all()
>>> exit()
```
---
### Step 6: Create API Resources
Define endpoints for CRUD operations. Each endpoint will correspond to a class
inheriting from `flask_restful.Resource`.
```python
# [Link]
from flask import request
from flask_restful import Resource
class UserResource(Resource):
def get(self, user_id):
user = [Link].get_or_404(user_id)
return {"id": [Link], "name": [Link], "age": [Link], "email":
[Link]}, 200
def post(self):
data = request.get_json()
new_user = User(name=data['name'], age=data['age'], email=data['email'])
[Link](new_user)
[Link]()
return {"message": "User created successfully"}, 201
def put(self, user_id):
data = request.get_json()
user = [Link].get_or_404(user_id)
[Link] = data['name']
[Link] = data['age']
[Link] = data['email']
[Link]()
return {"message": "User updated successfully"}, 200
def delete(self, user_id):
user = [Link].get_or_404(user_id)
[Link](user)
[Link]()
return {"message": "User deleted successfully"}, 204
```
---
### Step 7: Register API Endpoints
Add the following code to register the `UserResource` with the API.
```python
# [Link]
api.add_resource(UserResource, '/user/<int:user_id>', '/user')
```
---
### Step 8: Run the Application
Add the following code to the bottom of `[Link]` to run the Flask application.
```python
# [Link]
if __name__ == '__main__':
[Link](debug=True)
```
Run the application with:
```bash
python [Link]
```
---
### Step 9: Test the API
Use `curl` or Postman to test the API endpoints.
1. **Create a user** (POST):
```bash
curl -X POST -H "Content-Type: application/json" -d '{"name": "John Doe", "age":
30, "email": "john@[Link]"}' [Link]
```
2. **Get a user** (GET):
```bash
curl [Link]
```
3. **Update a user** (PUT):
```bash
curl -X PUT -H "Content-Type: application/json" -d '{"name": "John Doe", "age":
31, "email": "john_doe@[Link]"}' [Link]
```
4. **Delete a user** (DELETE):
```bash
curl -X DELETE [Link]
```
---
### 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.
---