blog bg

August 21, 2025

Creating a Custom API with Flask in Python

Share what you learn in this blog to prepare for your interview, create your forever-free profile now, and explore how to monetize your valuable knowledge.

Creating a Custom API with Flask in Python

 

APIs make it possible for apps to communicate to each other digitally in a world of microservices and frontend-backend structures. Flask is a lightweight but strong web platform that makes it easy and quick for Python developers to make their own APIs. You will learn how to make a simple custom REST API in Flask that can do all of the CRUD operations in this blogpost.

 

Why Flask?

With Flask, you can make micro web frameworks for Python. Developers have full control over how apps are organised and it is easy for beginners to use. Flask is great for small services, prototypes, and lightweight APIs because it does not push you into a certain project structure like Django does.

 

Benefits of Flask for APIs:

  • Fast and light
  • Simple to set up and expand
  • Large community and good documentation
  • Great for making RESTful APIs

 

Step 1: Install Flask

This is the first thing you need to do before writing any code.

Open your terminal and run:

pip install flask

 

Create a folder for your project:

mkdir flask-api
cd flask-api

Make a file inside the folder named app.py.

 

Step 2: Writing Your First API

First, let's write a simple Flask API that deals with users.

 

Project structure:

flask-api/
└── app.py

 

app.py

 

from flask import Flask, jsonify, request

app = Flask(__name__)

# In-memory database (list of dictionaries)
users = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"}
]

@app.route('/', methods=['GET'])
def home():
    return "Welcome to the Flask API!"

@app.route('/users', methods=['GET'])
def get_users():
    return jsonify(users)

@app.route('/user/<int:id>', methods=['GET'])
def get_user(id):
    user = next((u for u in users if u["id"] == id), None)
    return jsonify(user) if user else ("User not found", 404)

 

Explanation:

  • The @app.route tag defines a route (endpoint).
  • The function jsonify() turns Python objects into JSON.
  • To get dynamic data, you use route parameters like <int:id>.

 

Step 3: Adding POST, PUT, and DELETE Routes

Let's add full CRUD (Create, Read, Update, and Delete) functions to our API.

Put these routes in app.py below the existing ones.

@app.route('/user', methods=['POST'])
def add_user():
    new_user = request.get_json()
    if not new_user.get("id") or not new_user.get("name"):
        return jsonify({"error": "Missing fields"}), 400
   users.append(new_user)
    return jsonify(new_user), 201

@app.route('/user/<int:id>', methods=['PUT'])
def update_user(id):
    data = request.get_json()
    for user in users:
        if user["id"] == id:
           user.update(data)
            return jsonify(user)
    return jsonify({"error": "User not found"}), 404

@app.route('/user/<int:id>', methods=['DELETE'])
def delete_user(id):
    global users
    users = [u for u in users if u["id"] != id]
    return ("Deleted", 204)

 

Key Points:

  • POST adds a new user.
  • PUT modifies an existing user by ID.
  • DELETE removes a user.

 

Step 4: Running the Flask Server

To start your API locally:

 

On Mac/Linux:

export FLASK_APP=app.py
flask run

 

On Windows:

set FLASK_APP=app.py
flask run

 

Visit http://localhost:5000/users to see the JSON list of users.

 

Step 5: Testing the API

You can use Postman, Insomnia, or even curl to test the API.

 

Example with curl:

 

GET all users:

curl http://localhost:5000/users

 

POST new user:

curl -X POST -H "Content-Type: application/json" \
    -d '{"id": 3, "name": "Charlie"}' http://localhost:5000/user

 

PUT update user:

curl -X PUT -H "Content-Type: application/json" \
    -d '{"name": "Charles"}' http://localhost:5000/user/3

 

DELETE a user:

curl -X DELETE http://localhost:5000/user/3

 

Tips and Best Practices

  • Postman makes it easier to test with UI.
  • Split your code into different files (routes, models, etc.) as your app gets bigger.
  • Use authentication (like JWT) to make it safer.
  • Use unittest or pytest to write unit tests.

Do not use in-memory lists; instead, use a real database like SQLite or PostgreSQL.

 

Conclusion

You just used Flask to make a custom REST API that works perfectly! Flask lets you make clean and powerful web services with just a few lines of code. For testing, internal tools, or even production with the right changes, this setup is great.

You can follow these steps after learning the basics:

  • Use SQLAlchemy to add database support.
  • Use services like Render, Heroku, or Railway to deploy your Flask API online.
  • Make the API documentation use Swagger.

You can use Python's power with Flask. Now go make something awesome!

361 views

Please Login to create a Question