Open In App

Flask Creating Rest APIs

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A REST API (Representational State Transfer API) is a way for applications to communicate over the web using standard HTTP methods. It allows clients (such as web or mobile apps) to interact with a server by sending requests and receiving responses, typically in JSON format.

REST APIs follow a stateless architecture, meaning each request from a client to the server is independent and does not rely on previous requests. This makes REST APIs scalable, flexible, and easy to integrate with different platforms.

Key Features of REST APIs:

1. Uses standard HTTP methods for CRUD operations:

  • GET – Retrieve data
  • POST – Send new data
  • PUT – Update existing data
  • DELETE – Remove data

2. Follows a stateless design (each request is processed independently).

3. Uses JSON or XML for structured data exchange.

4. Enables easy integration with web, mobile, and third-party services.

Installation and Setting Up Flask

Create a project folder and then inside that folder create and activate a virtual environment to install flask and other necessary modules in it. Use these commands to create and activate a new virtual environment:

python -m venv venv
.venv\Scripts\activate

And after that install flask using this command:

pip install Flask

Creating API Routes for CRUD Operations

A REST API typically performs CRUD (Create, Read, Update, Delete) operations. In Flask, we define API routes using @app.route().

To demonstrate how to define REST APIs in Flask, we will create a simple Flask application that manages a collection of books. Our API will allow users to view, add, update, and delete books. Here is the code for the app:

Python
from flask import Flask, jsonify, request

app = Flask(__name__)

# Sample data
books = [
    {"id": 1, "title": "Concept of Physics", "author": "H.C Verma"},
    {"id": 2, "title": "Gunahon ka Devta", "author": "Dharamvir Bharti"},
    {"id": 3, "title": "Problems in General Physsics", "author": "I.E Irodov"}
]

# Get all books
@app.route('/books', methods=['GET'])
def get_books():
    return jsonify(books)

# Get a single book by ID
@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
    book = next((book for book in books if book["id"] == book_id), None)
    return jsonify(book) if book else (jsonify({"error": "Book not found"}), 404)

# Add a new book
@app.route('/books', methods=['POST'])
def add_book():
    new_book = request.json
    books.append(new_book)
    return jsonify(new_book), 201

# Update a book
@app.route('/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
    book = next((book for book in books if book["id"] == book_id), None)
    if not book:
        return jsonify({"error": "Book not found"}), 404

    data = request.json
    book.update(data)
    return jsonify(book)

# Delete a book
@app.route('/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
    global books
    books = [book for book in books if book["id"] != book_id]
    return jsonify({"message": "Book deleted"})

if __name__ == '__main__':
    app.run(debug=True)

Explanation of API Routes

  • GET /books - This route retrieves all books from our dataset and returns them in JSON format.
  • GET /books/<book_id> - This retrieves a single book based on its ID. If the book is not found, it returns a 404 error.
  • POST /books - This allows users to add a new book to the dataset by sending a JSON payload containing the book details.
  • PUT /books/<book_id> - This updates an existing book’s details based on the provided book ID. If the book is not found, it returns an error.
  • DELETE /books/<book_id> - This removes a book from the dataset based on the book ID and returns a confirmation message.

Testing The API Using Postman

We can test out API using Postman application so make sure you it installed on your system, if not, then download and install it from here. Run the application using this command in terminal and then open postman app:

python app.py

1. In the postman app, make a GET Request to the URL - "http://127.0.0.1:5000/books" to view all the books.

Rest-api1
Getting all books

2. Now to get a single book make a GET Request to this URL- "http://127.0.0.1:5000/books/1":

Rest-api2
Fetching a single book

To Post a new book data into the list we can make a POST Request to this URL - "http://127.0.0.1:5000/books" and provide the data of the new book data in JSON format under the boy tag in postman app:

Rest-api3
Posting data into the list

From the above snapshot, we can see that the Response Status is 201 CREATED, which means that the post request was successful. Similarly we can perform every CRUD operation using the postman app.


Next Article
Article Tags :
Practice Tags :

Similar Reads