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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read