> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Setting up Flask for the API

> Guide to scaffolding a minimal Flask API using an application factory, correctly registering routes within the app context, avoiding 404s, and using Blueprints or run.py entrypoint.

In this lesson you’ll scaffold a minimal Flask API using the application factory pattern, learn how to avoid common pitfalls that lead to 404s, and verify that your routes are registered on the running app instance.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/saITvJxm5YlZa_WW/images/AI-Assisted-Development/Development-Phase-Backend/Setting-up-Flask-for-the-API/flask-api-setup-demo-slide.jpg?fit=max&auto=format&n=saITvJxm5YlZa_WW&q=85&s=613dabc2f7e270e3dff21997fa6638fd" alt="A presentation slide titled &#x22;Setting Up Flask for the API&#x22; with a large, blue &#x22;Demo&#x22; label on a dark curved shape to the right. The slide also shows a small &#x22;© Copyright KodeKloud&#x22; at the bottom left." width="1920" height="1080" data-path="images/AI-Assisted-Development/Development-Phase-Backend/Setting-up-Flask-for-the-API/flask-api-setup-demo-slide.jpg" />
</Frame>

Overview

* Use an application factory `create_app()` in `app/__init__.py` to build your Flask app.
* Keep templates under `app/templates/`.
* Register routes while an application context is active so handlers attach to the same app instance the server runs.
* Start the server via `FLASK_APP` or an explicit `run.py` entrypoint.

Why this matters (keywords): Flask application factory, app context, Blueprints, route registration, FLASK\_APP, debugging Flask routes.

## Application factory (app/**init**.py)

Create the Flask app inside a factory so configuration and extensions can be initialized in one place. Import modules that register routes while an application context is active so their decorators attach to the same app instance returned by the factory.

Example `app/__init__.py` (clean, minimal):

```python theme={null}
from flask import Flask

def create_app():
    app = Flask(__name__, instance_relative_config=True)

    # Simple dev secret — change in production
    app.config.from_mapping(
        SECRET_KEY='dev',
    )

    # Load instance config if provided (silent=True won't raise if file missing)
    app.config.from_pyfile('config.py', silent=True)

    # Register routes (import while app context is active)
    with app.app_context():
        from . import routes  # Import registers handlers on `app`
        print("Routes imported successfully")

    return app
```

Key points:

* Import `routes` inside `with app.app_context()` so decorators like `@app.route` attach to this app instance.
* Use `instance_relative_config=True` for per-deployment overrides without committing secrets to source control.

## Base HTML template

For simple development or sanity checks you can include a minimal template. If you later build a frontend in React or another framework, the API can remain separate.

Example `app/templates/base.html`:

```html theme={null}
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Flask App</title>
</head>
<body>
    <h1>Welcome to My Flask App</h1>
    {% block content %}{% endblock %}
</body>
</html>
```

## Common pitfalls and how to debug them

1. FLASK\_APP not found

* Symptom: `Error: Could not import 'run'` — Flask cannot locate the module/file specified by `FLASK_APP`.
* Fix: Ensure `run.py` is in the current working directory or set `FLASK_APP` to the correct import path.

Examples:

```bash theme={null}
# macOS / Linux
export FLASK_APP=run.py
flask run

# Windows (PowerShell)
$env:FLASK_APP = "run.py"
flask run
```

2. Every route returns 404

* Symptom: Server starts, but requests return 404.
* Root cause: Routes were registered on a different app instance than the one you started. A common anti-pattern is creating a new app inside `routes.py` by calling the factory again.

Problematic pattern (DO NOT use this in `app/routes.py`):

```python theme={null}
# This will create a second app instance (problematic)
from . import create_app

app = create_app()   # <-- avoid creating a new app in routes.py

@app.route('/')
def home():
    return render_template('base.html')
```

3. Correct minimal pattern: register routes against the running app

* Option A (minimal): Use the `current_app` proxy so decorators attach to the active app when `routes` is imported inside the factory's app context.
* Option B (recommended for larger apps): Use Blueprints—define endpoints in Blueprints and register them inside `create_app()`.

Corrected minimal `app/routes.py` (using `current_app` proxy):

```python theme={null}
from flask import render_template
from flask import current_app as app

@app.route('/')
def home():
    return render_template('base.html')

@app.route('/about')
def about():
    return "About Page"

@app.route('/routes')
def show_routes():
    output = []
    for rule in app.url_map.iter_rules():
        output.append(f"{rule.endpoint}: {rule.rule}")
    return "<br>".join(output)
```

<Callout icon="lightbulb" color="#1CB2FE">
  For larger apps, prefer Blueprints. Define a Blueprint in `routes.py`, register it in `create_app()`, and avoid importing or creating the app inside route modules.
</Callout>

## Entry point (run.py)

Keep one entrypoint at the project root that creates the app via the factory and runs it. This file is what `FLASK_APP` should reference (or you can use it directly).

Example `run.py`:

```python theme={null}
from app import create_app

app = create_app()

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

## Debugging registered routes

* Add a `/routes` endpoint (like the example above) to list registered routes.
* Print `app.url_map` or a simple confirmation message (e.g., "Routes imported successfully") during startup to verify route registration.
* Ensure you import `routes` while the app context is active (inside `create_app()`).

404 example and diagnosis

* If you hit `http://127.0.0.1:5000/routes` and see a 404 page, that indicates the running app instance does not have a handler for `/routes` — usually because routes were attached to a different app instance.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/saITvJxm5YlZa_WW/images/AI-Assisted-Development/Development-Phase-Backend/Setting-up-Flask-for-the-API/localhost-5000-404-not-found.jpg?fit=max&auto=format&n=saITvJxm5YlZa_WW&q=85&s=b3990c2d56e8498cdfe6e9522d8537cd" alt="A web browser window (Chrome) showing a &#x22;Not Found&#x22; 404 error page from 127.0.0.1:5000/routes. The page displays a large &#x22;Not Found&#x22; headline and a message saying the requested URL was not found on the server." width="1920" height="1080" data-path="images/AI-Assisted-Development/Development-Phase-Backend/Setting-up-Flask-for-the-API/localhost-5000-404-not-found.jpg" />
</Frame>

Example console output (before fixing route registration):

```bash theme={null}
* Serving Flask app 'run.py'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
127.0.0.1 - - [DATE TIME] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [DATE TIME] "GET /routes HTTP/1.1" 404 -
```

After adjusting `app/__init__.py` to import routes inside the app context (and ensuring `routes.py` does not call `create_app()`), you should see successful imports and 200 responses:

Example console output (after fix):

```bash theme={null}
Routes imported successfully
* Serving Flask app 'run.py'
* Debug mode: off
* Running on http://127.0.0.1:5000
127.0.0.1 - - [DATE TIME] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [DATE TIME] "GET /routes HTTP/1.1" 200 -
```

## Quick checklist to fix "404 for all routes"

| Issue | Likely cause | Fix |
| - | - | - |
| `Error: Could not import 'run'` | `FLASK_APP` points to a missing file | Ensure `FLASK_APP` is set to `run.py` (or the correct module) and run from the project root: `export FLASK_APP=run.py` |
| All endpoints 404 | Routes registered on a different app instance | Ensure `run.py` calls `create_app()` and `app/__init__.py` imports `routes` inside `with app.app_context():` |
| `routes.py` creates an app | `create_app()` called twice — routes attach to different app | Do not call `create_app()` inside `routes.py`. Use `current_app` or Blueprints instead |
| Need route visibility | Hard to inspect registered routes | Add a `/routes` endpoint or print `app.url_map` during startup |

## Next steps

With the Flask scaffold in place and route registration verified, the next lesson will add endpoints to upload and process images (for example using OpenCV). Suggested reading and references:

* Flask documentation: [https://flask.palletsprojects.com/](https://flask.palletsprojects.com/)
* Flask application factory pattern: [https://flask.palletsprojects.com/en/latest/patterns/appfactories/](https://flask.palletsprojects.com/en/latest/patterns/appfactories/)
* Blueprints (recommended for modular apps): [https://flask.palletsprojects.com/en/latest/blueprints/](https://flask.palletsprojects.com/en/latest/blueprints/)

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/ai-assisted-development/module/0f8882f1-0976-491e-8243-9b522243717f/lesson/0a7e86ec-8050-4dad-b694-06e0b1677d7e" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.