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.
Getting all books2. Now to get a single book make a GET Request to this URL- "http://127.0.0.1:5000/books/1":
Fetching a single bookTo 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:
Posting data into the listFrom 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.
Similar Reads
Creating First REST API with FastAPI
FastAPI is a cutting-edge Python web framework that simplifies the process of building robust REST APIs. In this beginner-friendly guide, we'll walk you through the steps to create your very first REST API using FastAPI. By the end, you'll have a solid foundation for building and deploying APIs with
5 min read
Flask RESTFUL Extension
Flask-RESTful is an extension for Flask that simplifies the process of building REST APIs. It provides additional tools for creating APIs with minimal boilerplate code while following REST principles. With Flask-RESTful, defining API resources, handling requests, and formatting responses become more
5 min read
Django REST API - CRUD with DRF
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around the Django Framework. There are three stages before creating an API through the REST framework, Converting a Modelâs data to JSON/XML format (Serialization), Rendering this data to the view, and Cr
7 min read
Building RESTful APIs with FastAPI
FastAPI is a Python web framework that makes it easy to build APIs quickly and efficiently. There is Another famous framework for doing the same is Flask, which is also Python-based. In this article, we will focus on creating a RESTful API using FastAPI. In this article, we will learn how to create
5 min read
How to Connect ReactJS with flask API ?
Connecting React with Flask API allows us to create a full-stack web application with React handling the user interface at frontend and Flask serving the data in backend. Here React makes the HTTP request to interact with the flask API to perform operations with the database. ApproachTo connect Reac
4 min read
Browsable API in Django REST Framework
The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header. It helps us to use we
8 min read
Dockerize your Flask App
Deploying a Flask application manually can lead to dependency issues and inconsistencies across different environments. Docker solves this problem by packaging applications into containers, ensuring they run seamlessly on any system.In this article, weâll learn how to Dockerize a Flask app step by s
8 min read
FastAPI - Rest Architecture
FastAPI is a modern web framework for building APIs with Python. When developing a RESTful API with FastAPI, you can follow a REST architectural style, which stands for Representational State Transfer. In this article, we will learn about the FastAPI-Rest Architecture. Before going let's understand
9 min read
Flask NEWS Application Using Newsapi
In this article, we will create a News Web Application using Flask and NewsAPI. The web page will display top headlines and a search bar where the user can enter a query, after processing the query, the webpage will display all relevant articles (up to a max of 100 headlines). We will create a simpl
7 min read
Documenting RESTful APIs with Swagger
RESTful APIs play an important role in communicating between various software components. The interface used to consume APIs significantly impacts the chances of achieving business and technological objectives. In this article, we'll dive into the importance of RESTful API documentation and how Swag
8 min read