Visiors

A Beginner's Guide to Building REST APIs with Python Flask


Fast, Simple, Powerful

Flask is ideal for lightweight APIs and microservices. You define routes, handle requests, and connect databases effortlessly. Add JWT authentication, rate limiting, and Swagger documentation for production-ready APIs.

Flask's flexibility makes it perfect for both small tools and scalable backends.

In the age of digital platforms, mobile applications, microservices, and cloud-native architectures, REST APIs have become the backbone of modern software development. Whether you're building a simple note-taking app, a real-time dashboard, an e-commerce backend, or a scalable SaaS product, APIs are essential for communication between the frontend and backend.

Python, with its simplicity and rich ecosystem, is one of the most popular languages for building APIs. And among its frameworks, Flask stands out as a lightweight, flexible, and beginner-friendly choice. Flask makes it incredibly easy to build REST APIs quickly—without unnecessary complexity.

This in-depth beginner’s guide will walk you through:

  • What REST APIs are

  • Why Flask is perfect for beginners

  • Setup & installation

  • Creating your first API

  • Handling routes, requests, responses, and errors

  • Working with JSON

  • CRUD operations

  • Connecting to a database

  • Best practices

  • Deployment tips

  • Real-world examples

Let’s start from the basics and build your understanding step by step.


1. What is a REST API?

A REST API (Representational State Transfer) is an architectural style that allows systems to communicate over HTTP using standardized operations such as:

  • GET → retrieve data

  • POST → create data

  • PUT → update data

  • DELETE → delete data

REST APIs allow different systems (frontend, mobile apps, databases, microservices) to communicate seamlessly.


2. Why Use Flask for Building REST APIs?

Flask is popular because it is:

✔ Lightweight & Flexible

You can start with a few lines of code.

✔ Beginner-Friendly

Minimal setup, easy to understand.

✔ Extensible

Add libraries such as:

  • Flask-RESTful

  • Flask-JWT

  • Flask-SQLAlchemy

  • Flask-CORS

✔ Pythonic

Clean, readable syntax.

✔ Production Ready

Used by thousands of real-world applications.

Flask is ideal for both beginners and advanced developers building microservices or APIs at scale.


3. Setting Up Your Environment

Before building an API, install Python 3.8+ and Flask.

Step 1: Create a project folder

mkdir flask_api_demo cd flask_api_demo

Step 2: Create a virtual environment

python3 -m venv venv source venv/bin/activate # macOS/Linux venv\Scripts\activate # Windows

Step 3: Install Flask

pip install flask

4. Your First Flask REST API

Create a file named app.py:

from flask import Flask, jsonify app = Flask(__name__) @app.route('/api/hello', methods=['GET']) def hello(): return jsonify({"message": "Hello, Flask API!"}) if __name__ == "__main__": app.run(debug=True)

Run the API:

python app.py

Visit:

http://127.0.0.1:5000/api/hello

You’ll see:

{"message": "Hello, Flask API!"}

Congratulations — you’ve built your first API endpoint!


5. Understanding Routes and Methods

Routes define the URL paths your API responds to.

Example with multiple methods:

@app.route('/api/items', methods=['GET', 'POST']) def items(): if request.method == 'GET': return jsonify({"status": "GET request"}) elif request.method == 'POST': return jsonify({"status": "POST request"})

REST methods:

  • GET → List items

  • POST → Create item

  • PUT → Update item

  • DELETE → Delete item


6. Working with JSON Data

APIs generally send and receive JSON.

Example:

from flask import request @app.route('/api/data', methods=['POST']) def get_data(): data = request.get_json() return jsonify({"received": data})

Send JSON using Postman or cURL:

curl -X POST http://127.0.0.1:5000/api/data -H "Content-Type: application/json" -d "{\"name\":\"Rohit\"}"

7. Building a CRUD REST API with Flask

Let’s build a simple CRUD API for managing books.

In-memory data:

books = [ {"id": 1, "title": "Book One", "author": "Author A"}, {"id": 2, "title": "Book Two", "author": "Author B"} ]

7.1 GET All Books

@app.route('/api/books', methods=['GET']) def get_books(): return jsonify(books)

7.2 GET Book by ID

@app.route('/api/books/<int:id>', methods=['GET']) def get_book(id): book = next((b for b in books if b["id"] == id), None) return jsonify(book) if book else ({"error": "Book not found"}, 404)

7.3 POST: Add a New Book

@app.route('/api/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

7.4 PUT: Update Book

@app.route('/api/books/<int:id>', methods=['PUT']) def update_book(id): book = next((b for b in books if b["id"] == id), None) if not book: return {"error": "Book not found"}, 404 data = request.get_json() book.update(data) return jsonify(book)

7.5 DELETE: Remove Book

@app.route('/api/books/<int:id>', methods=['DELETE']) def delete_book(id): global books books = [b for b in books if b["id"] != id] return {"message": "Book deleted"}

You now have a fully functional CRUD API.


8. Using Flask-RESTful for Cleaner API Code

Install:

pip install flask-restful

Example:

from flask_restful import Api, Resource api = Api(app) class Hello(Resource): def get(self): return {"message": "Hello from Flask-RESTful"} api.add_resource(Hello, '/api/hello')

Flask-RESTful helps keep code modular and scalable.


9. Adding a Database (Flask + SQLAlchemy)

Install:

pip install flask_sqlalchemy

Setup:

from flask_sqlalchemy import SQLAlchemy app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///books.db" db = SQLAlchemy(app)

Model:

class Book(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100)) author = db.Column(db.String(100))

Create DB:

with app.app_context(): db.create_all()

You can now query and save data using SQLAlchemy.


10. Adding Authentication with Flask-JWT

Install:

pip install flask-jwt-extended

Usage:

from flask_jwt_extended import JWTManager, create_access_token app.config["JWT_SECRET_KEY"] = "secret" jwt = JWTManager(app)

Generate token:

token = create_access_token(identity="user1")

Protect routes:

@jwt_required() def protected_route(): return {"msg": "secure data"}

11. Cross-Origin Resource Sharing (CORS)

Install:

pip install flask-cors

Enable:

from flask_cors import CORS CORS(app)

Useful when frontend and backend run on different domains.


12. Error Handling

Custom errors:

@app.errorhandler(404) def not_found(e): return jsonify({"error": "Not Found"}), 404

13. Logging

import logging logging.basicConfig(level=logging.INFO)

14. Deployment Options

You can deploy Flask apps using:

1. Gunicorn + Nginx (Linux server)

2. Docker containers

3. Heroku

4. AWS Elastic Beanstalk

5. Google Cloud Run

6. Railway.app

7. Render.com

Basic production command:

gunicorn app:app

15. API Best Practices

✔ Use proper HTTP status codes

✔ Validate incoming data

✔ Use versioning (/api/v1/)

✔ Rate limiting for protection

✔ Pagination for large datasets

✔ Consistent JSON responses

✔ Secure with authentication


16. Real-World Example: Todo API Structure

Endpoints:

  • GET /api/todos

  • POST /api/todos

  • GET /api/todos/:id

  • PUT /api/todos/:id

  • DELETE /api/todos/:id

This forms the foundation of many production applications.


17. Conclusion: Start Small, Build Big

Flask provides an incredibly simple and flexible foundation for building REST APIs. From a basic "Hello World" endpoint to full-scale production-ready APIs with authentication and databases, Flask supports every stage of your development journey.

With a few lines of code, you can build:

  • microservices

  • mobile backends

  • IoT device APIs

  • web application backends

  • AI/ML model-serving APIs

Mastering REST APIs with Flask gives you a strong foundation in backend development and positions you for advanced frameworks like FastAPI, Django REST Framework, and scalable cloud architectures.

Previous Post Next Post