
A Beginner’s Guide to Building a REST API with Flask and SQLAlchemy
Learn how to build a simple REST API using Flask and SQLAlchemy in Python. This step-by-step guide covers setting up a virtual environment, configuring Flask, creating database models, and implementing CRUD operations. By the end, you'll have a working API that can manage resources efficiently, and you can further expand it for more complex use cases.
Building a REST API is a common task in modern web development. REST APIs allow for communication between a client (such as a web or mobile app) and a server to perform operations like retrieving, creating, updating, or deleting data. In this guide, we’ll walk through how to create a simple REST API using Flask, a lightweight web framework in Python, and SQLAlchemy, a powerful Object Relational Mapper (ORM).
Prerequisites
Before we begin, ensure you have Python installed on your system. You can check this by running:
bash
python --version
Step 1: Setting Up the Environment
First, let's create a virtual environment for our project and install the necessary dependencies.
bash
# Create a project folder and navigate into it mkdir flask_api cd flask_api # Create a virtual environment python -m venv venv # Activate the virtual environment # On Windows venv\Scripts\activate # On macOS/Linux source venv/bin/activate # Install Flask and SQLAlchemy pip install Flask SQLAlchemy
Step 2: Setting Up the Flask App
Next, let’s create a simple Flask application to serve as the foundation of our REST API.
python
from flask import Flask app = Flask(__name__)
@app.route('/') def index():
return "Welcome to our API"
if __name__ == '__main__':
app.run(debug=True)
Save this in a file called app.py
. To run the server, execute:
bash
python app.py
You should now be able to open a browser and navigate to http://127.0.0.1:5000/
to see the welcome message.
Step 3: Configuring SQLAlchemy
Now, let’s set up SQLAlchemy for database interactions. We’ll start by configuring the database and creating a simple model.
python
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///api.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app)
Let’s define a model representing a resource, such as a "Book" in a library:
python
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False) author = db.Column(db.String(100), nullable=False)
def __repr__(self):
return f'<Book {self.title}>'
Once the model is defined, create the database by running:
bash
# In Python shell
from app import db
db.create_all()
Step 4: Creating CRUD Routes
To make our API useful, we need to define routes for CRUD (Create, Read, Update, Delete) operations. Here’s how you can implement them:
python
from flask import request, jsonify
# Create a new book
@app.route('/books', methods=['POST'])
def add_book():
data = request.get_json()
new_book = Book(title=data['title'], author=data['author'])
db.session.add(new_book)
db.session.commit()
return jsonify({"message": "Book added"}), 201
# Get all books
@app.route('/books', methods=['GET'])
def get_books():
books = Book.query.all()
return jsonify([{"title": book.title, "author": book.author} for book in books])
# Update a book
@app.route('/books/<int:id>', methods=['PUT'])
def update_book(id):
book = Book.query.get(id)
if not book:
return jsonify({"message": "Book not found"}), 404
data = request.get_json()
book.title = data['title']
book.author = data['author']
db.session.commit()
return jsonify({"message": "Book updated"})
# Delete a book
@app.route('/books/<int:id>', methods=['DELETE'])
def delete_book(id):
book = Book.query.get(id)
if not book:
return jsonify({"message": "Book not found"}), 404
db.session.delete(book)
db.session.commit()
return jsonify({"message": "Book deleted"})
Step 5: Testing the API
You can now test the API using tools like Postman or cURL. Here are some example requests:
- Add a book:
bash
curl -X POST http://127.0.0.1:5000/books \ -H "Content-Type: application/json" \ -d '{"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}'
- Get all books:
bash
curl http://127.0.0.1:5000/books
- Update a book:
bash
curl -X PUT http://127.0.0.1:5000/books/1 \ -H "Content-Type: application/json" \ -d '{"title": "The Great Gatsby", "author": "Fitzgerald"}'
- Delete a book:
bash
curl -X DELETE http://127.0.0.1:5000/books/1
Conclusion
In this guide, we covered the basic steps for setting up a REST API using Flask and SQLAlchemy. We’ve implemented the fundamental CRUD operations that serve as the backbone of many web applications. You can further extend this API by adding features like authentication, pagination, or connecting it to a more robust database like PostgreSQL.
This basic framework will allow you to build more complex applications as your needs evolve. Happy coding!
0 Comments