A REST API (Representational State Transfer API) is a way for applications to communicate over the web using standardHTTP 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 standardHTTPmethods forCRUDoperations:
- 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. UsesJSONorXMLfor structured data exchange.
4. Enables easyintegrationwith web, mobile, and third-party services.
Installation and Setting Up Flask
Create a project folder and then inside that folder create and activate avirtual environment to installflaskand other necessarymodulesin 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 performsCRUD(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 toview,add,update, anddeletebooks. Here is the code for the app:
PythonfromflaskimportFlask,jsonify,requestapp=Flask(__name__)# Sample databooks=[{"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'])defget_books():returnjsonify(books)# Get a single book by ID@app.route('/books/<int:book_id>',methods=['GET'])defget_book(book_id):book=next((bookforbookinbooksifbook["id"]==book_id),None)returnjsonify(book)ifbookelse(jsonify({"error":"Book not found"}),404)# Add a new book@app.route('/books',methods=['POST'])defadd_book():new_book=request.jsonbooks.append(new_book)returnjsonify(new_book),201# Update a book@app.route('/books/<int:book_id>',methods=['PUT'])defupdate_book(book_id):book=next((bookforbookinbooksifbook["id"]==book_id),None)ifnotbook:returnjsonify({"error":"Book not found"}),404data=request.jsonbook.update(data)returnjsonify(book)# Delete a book@app.route('/books/<int:book_id>',methods=['DELETE'])defdelete_book(book_id):globalbooksbooks=[bookforbookinbooksifbook["id"]!=book_id]returnjsonify({"message":"Book deleted"})if__name__=='__main__':app.run(debug=True)
Explanation of API Routes
- GET /books - This routeretrieves allbooks from our dataset and returns them in JSON format.
- GET /books/<book_id> - This retrievesa 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 bookto the dataset by sending a JSON payload containing the book details.
- PUT /books/<book_id> - Thisupdates 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> - Thisremoves 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 usingPostman application so make sure you it installed on your system, if not, then download and install it fromhere. Run the application using this command in terminal and then open postman app:
python app.py
1. In the postman app, make aGETRequest 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 aPOST Requestto 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 theResponse Status is201 CREATED, which means that the post request was successful. Similarly we can perform every CRUD operation using the postman app.