
Have you ever wondered how your favourite apps communicate with servers to fetch data in real-time? Or why tech companies obsess over APIs during interviews? The answer lies in understanding REST APIs—and trust me, creating a REST API using Python Flask isn’t as challenging as it sounds.
Here’s the thing: learning to create a REST API using Python Flask is like learning to ride a bike. Initially, it seems complex with all those endpoints, HTTP methods, and JSON responses floating around. But once you get the hang of it, you’ll realise it’s one of the most powerful skills in your tech arsenal.
Whether you’re a B.Tech student preparing for placements or a professional looking to add backend development to your skillset, this guide will take you from zero to building your first functional API.
What’s in it for you? By the end of this article, you’ll understand REST fundamentals, know how to set up Flask, create multiple endpoints, handle different HTTP methods, and even test your API like a pro. Moreover, you’ll have a working project that you can showcase in your portfolio or use as a foundation for bigger applications. Sound exciting? Let’s dive in.
Why Flask for Your First REST API?
Before we jump into coding, let’s address the elephant in the room: why Flask?
Think of Flask as the Swiss Army knife of Python web frameworks. It’s lightweight, easy to learn, and doesn’t force you into a specific way of doing things. Unlike Django, which comes with batteries included (and sometimes batteries you don’t need), Flask gives you just enough to get started. This makes it perfect for beginners because you’re not overwhelmed with features you don’t understand yet.
Also, Flask’s simplicity doesn’t mean it’s not powerful. Companies like Netflix, Reddit, and Airbnb use Flask in their tech stack. So you’re learning a production-ready framework, not just a toy for tutorials.
Understanding REST: The Foundation
Let’s get conceptual for a moment. REST (Representational State Transfer) is basically a set of rules for building APIs. Think of it as a language that allows your frontend to talk to your backend, or one service to communicate with another.
Imagine you’re at a restaurant. You (the client) don’t go into the kitchen to make your food. Instead, you tell the waiter (the API) what you want, and the waiter brings it from the kitchen (the server). REST APIs work similarly—they’re the intermediary that handles requests and delivers responses.
REST APIs use standard HTTP methods:
- GET: Retrieve data (like reading a menu)
- POST: Create new data (like placing an order)
- PUT: Update existing data (like modifying your order)
- DELETE: Remove data (like canceling an order)
Understanding these methods is crucial because they form the backbone of any REST API you’ll build.
Setting Up Your Development Environment
Alright, enough theory. Let’s get our hands dirty with code.
First, you’ll need Python installed on your system. If you’re reading this, I’m assuming you already have it. Now, let’s install Flask. Open your terminal and run:
bash
pip install flask
That’s it. Flask is installed. See what I meant by lightweight?
Pro tip: Use a virtual environment to keep your project dependencies isolated. It’s a good practice that’ll save you headaches later:
bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install flask
Your First Flask Application
Let’s create a simple “Hello World” API to understand the basics. Create a file called app.py and add this code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return {'message': 'Welcome to your first REST API!'}
if __name__ == '__main__':
app.run(debug=True)
Run this file with python app.py, and voila! Your API is running on http://127.0.0.1:5000/.
What’s happening here? We’re importing Flask, creating an app instance, and defining a route. The @app.route(‘/’) decorator tells Flask that when someone visits the root URL, execute the home() function. The debug=True parameter is particularly useful because it auto-reloads your server when you make changes and shows detailed error messages.
Building a Real-World Example: A Book Library API
Let’s build something practical—a simple book library API where you can add, view, update, and delete books. This will cover all CRUD (Create, Read, Update, Delete) operations.
First, let’s structure our data. In a real application, you’d use a database, but for learning purposes, we’ll use a Python list to store our books in memory:
from flask import Flask, jsonify, request
app = Flask(__name__)
# In-memory database (just a list)
books = [
{'id': 1, 'title': 'Clean Code', 'author': 'Robert Martin', 'year': 2008},
{'id': 2, 'title': 'The Pragmatic Programmer', 'author': 'Hunt & Thomas', 'year': 1999}
]
Notice we’re importing jsonify and request from Flask. The jsonify function converts Python dictionaries into proper JSON responses, and request helps us access incoming data from API calls.
Implementing GET Requests
Let’s create endpoints to retrieve books. We’ll need two: one to get all books and another to get a specific book by ID.
@app.route('/api/books', methods=['GET'])
def get_books():
return jsonify({'books': books, 'count': len(books)})
@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
return jsonify(book)
return jsonify({'error': 'Book not found'}), 404
Breaking this down: The first endpoint returns all books along with a count. The second endpoint uses a dynamic route parameter <int:book_id> which automatically converts the URL parameter to an integer. We then search for the book using a generator expression—a neat Python feature that’s memory-efficient.
Also, notice the 404 status code when a book isn’t found. Status codes are important in REST APIs because they tell clients what happened without parsing the response body.
Creating New Books with POST
Now let’s add functionality to create new books:
@app.route('/api/books', methods=['POST'])
def add_book():
new_book = request.get_json()
# Validate required fields
if not all(key in new_book for key in ['title', 'author', 'year']):
return jsonify({'error': 'Missing required fields'}), 400
# Generate new ID
new_book['id'] = max(book['id'] for book in books) + 1 if books else 1
books.append(new_book)
return jsonify(new_book), 201
The request.get_json() method extracts JSON data from the request body. We’re also validating that all required fields are present—always validate user input! Moreover, we’re returning a 201 status code, which specifically means “Created” in HTTP terminology.
Testing this: You can use tools like Postman or curl to send POST requests. Here’s a curl example:
bash
curl -X POST http://127.0.0.1:5000/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Python Tricks","author":"Dan Bader","year":2017}'
Updating Books with PUT
Updating resources is straightforward with PUT requests:
@app.route('/api/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
update_data = request.get_json()
# Update only provided fields
book.update({key: value for key, value in update_data.items()
if key in ['title', 'author', 'year']})
return jsonify(book)
This endpoint finds the book and updates only the fields that were provided in the request. The dictionary comprehension filters out any unwanted fields, which is a security best practice.
Deleting Books with DELETE
Finally, let’s implement deletion:
python
@app.route('/api/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
book = next((book for book in books if book['id'] == book_id), None)
if not book:
return jsonify({'error': 'Book not found'}), 404
books = [book for book in books if book['id'] != book_id]
return jsonify({'message': 'Book deleted successfully'})
We’re using a list comprehension to filter out the deleted book. Although this approach works for our simple example, in production applications you’d be running SQL DELETE queries on a database.
The Complete Application
Here’s how your complete app.py should look:
python
from flask import Flask, jsonify, request
app = Flask(__name__)
books = [
{'id': 1, 'title': 'Clean Code', 'author': 'Robert Martin', 'year': 2008},
{'id': 2, 'title': 'The Pragmatic Programmer', 'author': 'Hunt & Thomas', 'year': 1999}
]
@app.route('/api/books', methods=['GET'])
def get_books():
return jsonify({'books': books, 'count': len(books)})
@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book['id'] == book_id), None)
if book:
return jsonify(book)
return jsonify({'error': 'Book not found'}), 404
@app.route('/api/books', methods=['POST'])
def add_book():
new_book = request.get_json()
if not all(key in new_book for key in ['title', 'author', 'year']):
return jsonify({'error': 'Missing required fields'}), 400
new_book['id'] = max(book['id'] for book in books) + 1 if books else 1
books.append(new_book)
return jsonify(new_book), 201
@app.route('/api/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
update_data = request.get_json()
book.update({key: value for key, value in update_data.items()
if key in ['title', 'author', 'year']})
return jsonify(book)
@app.route('/api/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
global books
book = next((book for book in books if book['id'] == book_id), None)
if not book:
return jsonify({'error': 'Book not found'}), 404
books = [b for b in books if b['id'] != book_id]
return jsonify({'message': 'Book deleted successfully'})
if __name__ == '__main__':
app.run(debug=True)
Testing Your API
You’ve built the API, but how do you know it works? Testing is crucial.
The easiest way is using Postman—a popular API testing tool with a user-friendly interface. Alternatively, you can use Python’s requests library or curl from the command line.
Here’s a simple test script using Python:
python
import requests
BASE_URL = 'http://127.0.0.1:5000/api/books'
# Get all books
response = requests.get(BASE_URL)
print('All books:', response.json())
# Create a new book
new_book = {'title': 'Fluent Python', 'author': 'Luciano Ramalho', 'year': 2015}
response = requests.post(BASE_URL, json=new_book)
print('Created:', response.json())
Next Steps: Where to Go From Here
Congratulations! You’ve just built a functional REST API using Python Flask. But this is just the beginning.
Here are some ways to level up your API:
- Add a real database like PostgreSQL or MongoDB using Flask-SQLAlchemy
- Implement authentication with JWT tokens to secure your endpoints
- Add error handling middleware for consistent error responses
- Document your API using Flask-RESTX or Swagger
- Deploy your API to platforms like Heroku, AWS, or DigitalOcean
The beauty of Flask is that it grows with you. You can start simple and add complexity as you learn.
Wrapping Up
Building a REST API using Python Flask isn’t rocket science—it’s a learnable skill that opens doors in backend development. You’ve now got the foundation to build more complex applications, contribute to open-source projects, or ace that technical interview question about REST APIs.
Remember, the best way to solidify this knowledge is by building. Take this book library example and modify it—maybe create a todo list API, a blog API, or anything that interests you. The code patterns remain the same; only the domain changes.
Keep coding, keep experimenting, and don’t be afraid to break things. That’s how you learn. And who knows? The next big API powering millions of users might just start with you running python app.py on your local machine today.
Whether you’re preparing for exams or debugging tricky code, Techarticle has you covered! Explore our comprehensive collection of programming tutorials and data structures guides designed to make coding easier and more enjoyable.
Listed below are a few blog posts related to programming languages which might excite you:
The exciting list of top 5 programming languages for 2025
A Deep Dive into Programming Languages: Everything You Need to Know
How to Build a Calculator App in Python Using Tkinter
