REST API with Flask – Complete Guide with Examples

Introduction

Python provides many frameworks for API development, and Flask is one of the most popular choices because of its lightweight design and flexibility. Flask allows developers to quickly create RESTful APIs that can be used by web applications, mobile applications, and other services.

For example, a mobile application may request user data from a Flask REST API, the server processes the request, retrieves data from a database, and sends a response in JSON format.

What is an API?

API stands for Application Programming Interface.

An API allows two different applications to communicate with each other.

Example: A frontend application communicates with a database server.

A simple example flow:


 User Application
        |
        |
        ↓
       API
        |
        |
        ↓
 Server Database

The API receives requests, processes them, and sends responses.

What is a REST API?

REST stands for: Representational State Transfer

A REST API is an API architecture that allows applications to communicate using HTTP protocols.

REST APIs usually exchange data in:

  • JSON format
  • XML format

Most modern applications use REST APIs because they are lightweight and easy to integrate.

REST API Principles

REST follows several important principles.

1. Client-Server Architecture

The client and server work independently.

Example:


Frontend
    |
    |
 REST API
    |
    |
 Backend

2. Stateless Communication

Each request contains all required information.

The server does not store client session information between requests.

3. Resource-Based URLs

REST APIs represent data as resources.

Example:


/users
/products
/orders

4. HTTP Methods

REST uses HTTP methods to perform operations.

Common methods:

Method Purpose
GET Retrieve data
POST Create data
PUT Update data
DELETE Remove data

How to use Flask for a REST API?

There are many steps to use Flask.

1. Installing Flask

Install Flask using pip:


pip install flask

Verify installation:


pip show flask

2. Creating First Flask REST API

Create a file:


app.py

Example:


from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
    return {
        "message": "Welcome to REST API"
    }
if __name__ == "__main__":
    app.run()

3. Running Flask API

Execute:


python app.py

Output:

Running on http://127.0.0.1:5000

Open:


http://127.0.0.1:5000

Response:


{
    "message": "Welcome to REST API"
}

4. Understanding Flask API Code

Import Flask


from flask import Flask

Imports Flask framework.

Create Application


app = Flask(__name__)

Creates Flask application object.

Create Route


@app.route("/")

Defines API endpoint.

Return JSON Response


return {
"message":"Hello"
}

Flask automatically converts dictionary data into JSON.

5. Creating GET API

GET is used to retrieve data.

Example:


from flask import Flask
app = Flask(__name__)
users = [
    {
        "id":1,
        "name":"John"
    },
    {
        "id":2,
        "name":"David"
    }
]
@app.route("/users")
def get_users():
    return users
app.run()

API Response

URL:


/users

Response:


[
 {
  "id":1,
  "name":"John"
 },
 {
  "id":2,
  "name":"David"
 }
]

6. Creating POST API

POST is used to create new data.

Flask uses request to receive data.

Example:


from flask import request
@app.route("/users", methods=["POST"])
def add_user():
    data = request.json
    users.append(data)
    return {
        "message":"User Added"
    }

Sending POST Data

Request:


{
"name":"Alex",
"age":25
}
Response:
{
"message":"User Added"
}

7. Creating PUT API

PUT updates existing data.

Example:


@app.route(
"/users/",
methods=["PUT"]
)
def update_user(id):
    data=request.json
    users[id]=data
    return {
        "message":
        "User Updated"
    }

8. Creating DELETE API

DELETE removes data.

Example:


@app.route(
"/users/",
methods=["DELETE"]
)
def delete_user(id):
    users.pop(id)
    return {
        "message":
        "User Deleted"
    }

CRUD Operations Using Flask REST API

CRUD means:

Operation HTTP Method
Create POST
Read GET
Update PUT
Delete DELETE

Example:


User Management API
GET     /users
POST    /users
PUT     /users/1
DELETE  /users/1

9. Using Flask with JSON

JSON is the most common format used in REST APIs.

Example:


{
"id":1,
"name":"Python"
}
Python dictionary:
data = {
"id":1,
"name":"Python"
}

Flask converts Python objects into JSON responses.

10. Connecting Flask REST API with Database

Real applications store data in databases.

Common databases:

  • MySQL
  • PostgreSQL
  • SQLite
  • MongoDB

Flask can connect using extensions.

Example:


pip install flask-sqlalchemy

10. Flask REST API Project Structure

A professional API project may look like:


project/
│
├── app.py
│
├── models.py
│
├── routes.py
│
├── database.py
│
└── requirements.txt

How to Test a REST API?

APIs can be tested using:

  • Postman
  • Insomnia
  • Browser
  • cURL

Example:

GET request:


GET /users

POST request:


POST /users

Error Handling in Flask API

Errors should return meaningful responses.

Example:


@app.errorhandler(404)
def not_found(error):
    return {
        "error":
        "Resource Not Found"

    },404

HTTP Status Codes

Common API status codes:

Code Meaning
200 Success
201 Created
400 Bad Request
401 Unauthorized
404 Not Found
500 Server Error

How to use Authentication in Flask REST API?

Secure APIs use authentication, so you will see some common methods:

1. Token Authentication

User receives a token after login.

2. JWT Authentication

JSON Web Token is commonly used.

Install:


pip install flask-jwt-extended

Real-Life Applications of Flask REST API

1. Mobile Applications

Android and iOS apps communicate with backend APIs.

2. E-Commerce Applications: APIs manage:

  • Products
  • Orders
  • Payments

3. Social Media Platforms

APIs handle:

  • Posts
  • Comments
  • User profiles

4. Banking Applications

APIs process secure transactions.

Common Mistakes

1. Returning Invalid JSON

Incorrect:


return "data"

Better:


return {
"data":"value"
}

2. Not Using Correct HTTP Methods

Example:


Using GET for deleting data.

Correct:


DELETE /users/1

3. No Error Handling

Always handle:

  • Invalid requests
  • Missing data
  • Server errors

4. Exposing Sensitive Data

Never return:

  • Passwords
  • API keys
  • Private information

Best Practices

1. Use Meaningful URLs

Good:


/api/users

Bad:


/getUserData

2. Validate Input

Check user data before processing.

3. Use Authentication

Protect private endpoints.

4. Version APIs

Example:


/api/v1/users

5. Document APIs

Use tools like:

  • Swagger
  • OpenAPI

Conclusion

REST API with Flask is one of the most important skills for modern Python developers. Flask provides a simple and powerful way to build APIs that connect web applications, mobile applications, and external services.

Flask APIs can build professional, scalable backend systems.

Related Python Tutorials