If you're looking to turn your Python code into a web app or a fully functional API, Flask is a great place to start. It's lightweight, easy to use, and highly adaptable — making it a popular choice for developers at all levels.
In this guide, we’ll walk through how to build a simple RESTful API using Flask.
What is Flask?
Flask is a micro web framework written in Python. “Micro” means it doesn’t come bundled with extra tools like a database layer or form validation — giving you full control to structure your app however you want.
Setting Up Your First Flask API
We’ll create a small API for managing a collection of books. No database for now — we’ll use an in-memory list to simulate stored data.
- Install Flask Open your terminal and install Flask using pip:
pip install Flask
- Create app.py
from flask import Flask, jsonify, request
app = Flask(name)
Sample data
books = [
{"id": 1, "title": "1984", "author": "George Orwell"},
{"id": 2, "title": "Brave New World", "author": "Aldous Huxley"}
]
@app.route("/books", methods=["GET"])
def get_books():
return jsonify(books), 200
@app.route("/books/int:id", methods=["GET"])
def get_book(id):
book = next((b for b in books if b["id"] == id), None)
return (jsonify(book), 200) if book else ({"error": "Book not found"}, 404)
@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
if name == "main":
app.run(debug=True)
- Run the Server
python app.py
Visit http://localhost:5000/books in your browser
You should see the list of books in JSON format!
Why Use Flask?
Simple to get started
Great for building APIs and microservices
Works well with SQLAlchemy, Jinja, and other tools
You only include what you need
What’s Next?
Try extending the API by adding:
DELETE /books/ to remove a book
PUT /books/ to update an existing book
Integration with a SQLite database using SQLAlchemy
Wrap-Up
Flask is a fast and flexible way to get a Python web service running. Whether you’re building a prototype, a full-stack app, or a backend for a mobile project, Flask gives you just what you need — no more, no less.
Have questions or want to see the next step with databases or deployment? Let me know in the comments!
Top comments (0)