Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
83 views

How To Build A REST API With Flask

Uploaded by

Dex
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

How To Build A REST API With Flask

Uploaded by

Dex
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

# 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 `app.py` and set up a basic Flask application.

```python
# app.py
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 `app.py` to set up the
database.

```python
from flask_sqlalchemy import SQLAlchemy

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
```

---

### Step 5: Define a Data Model

Create a `User` model for storing users in the database.

```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})"
```

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
# 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

def put(self, user_id):


data = request.get_json()
user = User.query.get_or_404(user_id)
user.name = data['name']
user.age = data['age']
user.email = data['email']
db.session.commit()
return {"message": "User updated successfully"}, 200

def delete(self, user_id):


user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return {"message": "User deleted successfully"}, 204
```

---

### Step 7: Register API Endpoints

Add the following code to register the `UserResource` with the API.

```python
# app.py
api.add_resource(UserResource, '/user/<int:user_id>', '/user')
```

---

### Step 8: Run the Application

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)
```

Run the application with:

```bash
python app.py
```

---

### 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@example.com"}' http://127.0.0.1:5000/user
```

2. **Get a user** (GET):

```bash
curl http://127.0.0.1:5000/user/1
```

3. **Update a user** (PUT):

```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
```

4. **Delete a user** (DELETE):

```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.

---

You might also like