Last modified: Feb 01, 2026 By Alexander Williams

Build a Flask API with Python: Beginner's Guide

APIs are the backbone of modern web and mobile applications. They allow different software systems to communicate.

Flask is a popular Python framework for building web applications and APIs. It is known for being lightweight and easy to learn.

This guide will walk you through creating your first RESTful API with Flask. You will learn the core concepts step by step.

What is Flask?

Flask is a micro web framework written in Python. It is designed to be simple and extensible.

Unlike larger frameworks, Flask provides the basic tools you need. You can add extensions for more complex features like databases or authentication.

This makes it a perfect choice for building APIs quickly. It is especially good for prototypes and small to medium-sized projects.

Setting Up Your Flask Environment

First, you need to set up a Python environment. It is best practice to use a virtual environment.

This keeps your project's dependencies separate from other Python projects on your system.

Open your terminal or command prompt and follow these steps.


# Create a new directory for your project
mkdir my_flask_api
cd my_flask_api

# Create a virtual environment (venv is built into Python 3)
python -m venv venv

# Activate the virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

# Install Flask using pip
pip install flask
    

Creating Your First Flask Application

Now, let's create the simplest possible Flask app. Create a new file named app.py.

This file will contain the core logic of our API.


# Import the Flask class from the flask module
from flask import Flask

# Create an instance of the Flask class.
# __name__ helps Flask find templates and static files.
app = Flask(__name__)

# Define a route for the root URL ('/')
# The @app.route decorator tells Flask what URL triggers this function.
@app.route('/')
def home():
    # This function returns the data for the API endpoint.
    return {'message': 'Welcome to your first Flask API!'}

# This block ensures the app only runs if this script is executed directly.
if __name__ == '__main__':
    # Run the Flask development server.
    # debug=True enables auto-reload and better error messages.
    app.run(debug=True)
    

Save the file. Go back to your terminal, make sure your virtual environment is active, and run the app.


python app.py
    

You should see output indicating the server is running, typically at http://127.0.0.1:5000.

Open your web browser and go to that address. You will see the JSON response from your API.


{"message":"Welcome to your first Flask API!"}
    

Building a RESTful API with Routes

A RESTful API uses different HTTP methods (GET, POST, PUT, DELETE) on specific routes (URLs).

Let's build a simple API for managing a list of books. We will store data in a Python list for now.

Update your app.py file with the following code.


from flask import Flask, request, jsonify

app = Flask(__name__)

# In-memory "database" - a simple list of dictionaries.
# In a real app, you would use a database like SQLite or PostgreSQL.
books = [
    {'id': 1, 'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald'},
    {'id': 2, 'title': '1984', 'author': 'George Orwell'}
]

# GET /books - Retrieve all books
@app.route('/books', methods=['GET'])
def get_books():
    # The jsonify function converts the list to a proper JSON response.
    return jsonify({'books': books})

# GET /books/ - Retrieve a single book by ID
@app.route('/books/', methods=['GET'])
def get_book(book_id):
    # Find the book with the matching ID.
    book = next((b for b in books if b['id'] == book_id), None)
    if book is None:
        # Return a 404 error if the book is not found.
        return jsonify({'error': 'Book not found'}), 404
    return jsonify({'book': book})

# POST /books - Create a new book
@app.route('/books', methods=['POST'])
def create_book():
    # Check if the request contains JSON data.
    if not request.is_json:
        return jsonify({'error': 'Request must be JSON'}), 400

    data = request.get_json()
    # Simple validation: check for required fields.
    if 'title' not in data or 'author' not in data:
        return jsonify({'error': 'Missing title or author'}), 400

    # Create a new book object with a new ID.
    new_id = max(b['id'] for b in books) + 1 if books else 1
    new_book = {
        'id': new_id,
        'title': data['title'],
        'author': data['author']
    }
    books.append(new_book)
    # Return the new book with a 201 Created status code.
    return jsonify({'book': new_book}), 201

if __name__ == '__main__':
    app.run(debug=True)
    

Testing Your API Endpoints

You can test your API using a tool like curl in the terminal or an app like Postman.

Here are examples using curl to interact with your new book API.

1. Get All Books (GET request)


curl http://127.0.0.1:5000/books
    

Output:


{"books":[{"author":"F. Scott Fitzgerald","id":1,"title":"The Great Gatsby"},{"author":"George Orwell","id":2,"title":"1984"}]}
    

2. Get a Single Book (GET request)


curl http://127.0.0.1:5000/books/1
    

Output:


{"book":{"author":"F. Scott Fitzgerald","id":1,"title":"The Great Gatsby"}}
    

3. Create a New Book (POST request)


curl -X POST http://127.0.0.1:5000/books \
  -H "Content-Type: application/json" \
  -d '{"title": "To Kill a Mockingbird", "author": "Harper Lee"}'
    

Output:


{"book":{"author":"Harper Lee","id":3,"title":"To Kill a Mockingbird"}}
    

Connecting to a Database

For a real application, you need a proper database. Flask works well with many databases.

A common choice is SQLAlchemy, an Object-Relational Mapper (ORM). It lets you use Python classes to interact with your database.