Wednesday, November 5, 2025

thumbnail

How to Build a RESTful API with Flask

 ๐Ÿงฉ What You’ll Build


We’ll create a Book Management API with endpoints to:


Get all books


Get a book by ID


Add a new book


Update a book


Delete a book


All data will be stored in a simple in-memory list (you can later connect it to a database like SQLite or PostgreSQL).


⚙️ Step 1: Setup Your Environment

1️⃣ Install Flask

pip install flask



(Optional but recommended)


pip install flask-cors



flask-cors lets your API handle requests from different domains — useful when connecting to a frontend (e.g., React, Vue, Angular).


๐Ÿ“ Step 2: Create Project Structure

flask_api/

├── app.py            # Main application file

├── requirements.txt  # Dependencies

└── README.md


๐Ÿง  Step 3: Build the Basic Flask App


Open app.py and start with a minimal Flask setup:


from flask import Flask, jsonify


app = Flask(__name__)


@app.route('/')

def home():

    return jsonify({"message": "Welcome to the Book API!"})


if __name__ == '__main__':

    app.run(debug=True)



Run the app:


python app.py



Then open http://127.0.0.1:5000/

 in your browser — you’ll see the welcome message.


๐Ÿ“š Step 4: Create a Sample Dataset


Add a simple list of books above your routes:


books = [

    {"id": 1, "title": "The Pragmatic Programmer", "author": "Andrew Hunt"},

    {"id": 2, "title": "Clean Code", "author": "Robert C. Martin"}

]


๐Ÿงฑ Step 5: Add CRUD Endpoints

✅ GET all books

@app.route('/api/books', methods=['GET'])

def get_books():

    return jsonify(books)


✅ GET a single book by ID

@app.route('/api/books/<int:book_id>', methods=['GET'])

def get_book(book_id):

    book = next((b for b in books if b["id"] == book_id), None)

    if book:

        return jsonify(book)

    return jsonify({"error": "Book not found"}), 404


✅ POST (Create) a new book

from flask import request


@app.route('/api/books', methods=['POST'])

def add_book():

    data = request.get_json()

    new_book = {

        "id": len(books) + 1,

        "title": data.get("title"),

        "author": data.get("author")

    }

    books.append(new_book)

    return jsonify(new_book), 201


✅ PUT (Update) an existing book

@app.route('/api/books/<int:book_id>', methods=['PUT'])

def update_book(book_id):

    data = request.get_json()

    book = next((b for b in books if b["id"] == book_id), None)

    if book is None:

        return jsonify({"error": "Book not found"}), 404


    book["title"] = data.get("title", book["title"])

    book["author"] = data.get("author", book["author"])

    return jsonify(book)


✅ DELETE a book

@app.route('/api/books/<int:book_id>', methods=['DELETE'])

def delete_book(book_id):

    global books

    books = [b for b in books if b["id"] != book_id]

    return jsonify({"message": "Book deleted"}), 200


๐Ÿงฉ Full app.py Example


Here’s the full working code:


from flask import Flask, jsonify, request

from flask_cors import CORS


app = Flask(__name__)

CORS(app)


books = [

    {"id": 1, "title": "The Pragmatic Programmer", "author": "Andrew Hunt"},

    {"id": 2, "title": "Clean Code", "author": "Robert C. Martin"}

]


@app.route('/')

def home():

    return jsonify({"message": "Welcome to the Book API!"})


@app.route('/api/books', methods=['GET'])

def get_books():

    return jsonify(books)


@app.route('/api/books/<int:book_id>', methods=['GET'])

def get_book(book_id):

    book = next((b for b in books if b["id"] == book_id), None)

    if book:

        return jsonify(book)

    return jsonify({"error": "Book not found"}), 404


@app.route('/api/books', methods=['POST'])

def add_book():

    data = request.get_json()

    new_book = {

        "id": len(books) + 1,

        "title": data.get("title"),

        "author": data.get("author")

    }

    books.append(new_book)

    return jsonify(new_book), 201


@app.route('/api/books/<int:book_id>', methods=['PUT'])

def update_book(book_id):

    data = request.get_json()

    book = next((b for b in books if b["id"] == book_id), None)

    if not book:

        return jsonify({"error": "Book not found"}), 404


    book["title"] = data.get("title", book["title"])

    book["author"] = data.get("author", book["author"])

    return jsonify(book)


@app.route('/api/books/<int:book_id>', methods=['DELETE'])

def delete_book(book_id):

    global books

    books = [b for b in books if b["id"] != book_id]

    return jsonify({"message": "Book deleted"}), 200


if __name__ == '__main__':

    app.run(debug=True)


๐Ÿงช Step 6: Test Your API


You can test your endpoints with:


✅ cURL

curl http://127.0.0.1:5000/api/books


✅ Postman or Thunder Client


GET → /api/books


POST → /api/books


{ "title": "Fluent Python", "author": "Luciano Ramalho" }



PUT → /api/books/1


{ "title": "Updated Title" }



DELETE → /api/books/2


๐Ÿ—„️ Step 7: (Optional) Connect to a Database


You can integrate Flask-SQLAlchemy to persist data.


Install:


pip install flask_sqlalchemy



Example setup:


from flask_sqlalchemy import SQLAlchemy


app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///books.db'

db = SQLAlchemy(app)


class Book(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    title = db.Column(db.String(120), nullable=False)

    author = db.Column(db.String(120), nullable=False)



Run:


from app import db

db.create_all()



Now you can replace the list-based logic with database queries.


๐Ÿ” Step 8: Add Security & Best Practices

Security Feature Flask Extension Description

CORS flask-cors Allow cross-origin requests safely

Auth flask-jwt-extended Add JWT authentication

Validation marshmallow Validate request payloads

Rate limiting flask-limiter Prevent abuse and DDoS


Example JWT setup:


pip install flask-jwt-extended


☁️ Step 9: Deploy Your Flask API


You can deploy easily to:


Render, Railway, or Heroku


AWS, Azure, or Google Cloud


Using Docker:


FROM python:3.12

WORKDIR /app

COPY . .

RUN pip install -r requirements.txt

CMD ["python", "app.py"]


✅ Summary

Step Description

1️⃣ Install Flask and set up project

2️⃣ Create endpoints for CRUD operations

3️⃣ Use JSON for input/output

4️⃣ Test with Postman or curl

5️⃣ Add persistence with SQLAlchemy

6️⃣ Secure your API (CORS, JWT, etc.)

7️⃣ Deploy to the cloud

Learn Fullstack Python Training in Hyderabad

Read More

Introduction to REST APIs with Python

Building APIs with Python

Encrypting Sensitive Data in Full Stack Python Apps

Common Web Security Vulnerabilities and How to Protect Against Them

At Our Quality Thought Training Institute in Hyderabad

Get Directions


Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive