The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
A clean, beginner-friendly explanation and example of how to implement a
simple RESTAPI using Flask.
1. Install Flask
pip install flask
2. Create the app structure
project/
└── app.py
3. Basic REST API Example (CRUD)
Here is a complete working example that implements:
GET (read all)
GET by ID
POST (create)
PUT (update)
DELETE (remove)
app.py
from flask import Flask, jsonify, request
app = Flask(__name__)
# Fake in-memory database
books = [
{"id": 1, "title": "Book One", "author": "Author A"},
{"id": 2, "title": "Book Two", "author": "Author B"},
]
# GET all books
@app.route("/books", methods=["GET"])
def get_books():
return jsonify(books)
# GET book by ID
@app.route("/books/<int:book_id>", methods=["GET"])
def get_book(book_id):
book = next((b for b in books if b["id"] == book_id), None)
return jsonify(book) if book else ("Not Found", 404)
# POST → Create new book
@app.route("/books", methods=["POST"])
def add_book():
data = request.get_json()
new_book = {
"id": books[-1]["id"] + 1 if books else 1,
"title": data["title"],
"author": data["author"]
}
books.append(new_book)
return jsonify(new_book), 201
# PUT → Update book
@app.route("/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 ("Not Found", 404)
book["title"] = data.get("title", book["title"])
book["author"] = data.get("author", book["author"])
return jsonify(book)
# DELETE → Remove book
@app.route("/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 ("Deleted", 204)
if __name__ == "__main__":
app.run(debug=True)
4. Run the API
python app.py
Flask will start at:
http://127.0.0.1:5000
Test the API using cURL or Postman
GET all
GET http://127.0.0.1:5000/books
POST
POST http://127.0.0.1:5000/books
Content-Type: application/json
{
"title": "New Book",
"author": "New Author"
}
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
1. Install Flask
2. Create the app structure
3. Basic REST API Example (CRUD)
Here is a complete working example that implements:
app.py
4. Run the API
Flask will start at:
Test the API using cURL or Postman
GET all
POST