# Python REST API libraries

Python REST API frameworks receive HTTP requests, route them to handler functions, and return JSON responses. An ASGI framework accepts async endpoints and runs them on an event loop rather than through synchronous WSGI workers. These libraries let backend services expose their data and actions to apps and AI agents over HTTP.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Starlette](#starlette) | 706.4M | 12.7K | Oct 2026 | BSD-3-Clause |
| [aiohttp](#aiohttp) | 562.2M | 16.6K | Oct 2026 | Apache-2.0 AND MIT |
| [FastAPI](#fastapi) | 544.0M | 104.9K | Nov 2026 | MIT |
| [Flask](#flask) | 208.0M | 75.2K | Feb 2026 | BSD-3-Clause |
| [Tornado](#tornado) | 122.3M | 22.2K | Nov 2026 | Apache-2.0 |
| [Django](#django) | 51.9M | 91.8K | Nov 2026 | BSD-3-Clause |
| [Django REST framework](#django-rest-framework) | 30.2M | 30.2K | Oct 2026 | BSD-3-Clause |
| [Bottle](#bottle) | 9.6M | 8.8K | Jun 2025 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Starlette](#starlette) has the most monthly downloads in this comparison, at 706.4M.

## Capabilities

| Library | Async def handlers | Automatic JSON body schemas |
| --- | --- | --- |
| [Starlette](#starlette) | Yes | No |
| [aiohttp](#aiohttp) | Yes | No |
| [FastAPI](#fastapi) | Yes | Yes |
| [Flask](#flask) | Yes | No |
| [Tornado](#tornado) | Yes | No |
| [Django](#django) | Yes | No |
| [Django REST framework](#django-rest-framework) | No | Yes |
| [Bottle](#bottle) | No | No |

## Libraries

### Starlette

[GitHub](https://github.com/Kludex/starlette) · [PyPI](https://pypi.org/project/starlette) · [Docs](https://www.starlette.io/)

Builds web applications on ASGI.

- Downloads / mo: 706.4M
- Stars: 12.7K
- Last release: 1.10.0
- License: BSD-3-Clause
- Capabilities: [From the Starlette docs](https://www.starlette.io/)

```sh
python -m pip install starlette==1.10.0 uvicorn
```

**Quickstart**

```python
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def status(request):
    return JSONResponse({"message": "Hello"})

app = Starlette(routes=[Route("/api/status", status)])

```

From [index.html](https://www.starlette.io/) · [Find projects using Starlette →](https://dashboard.exa.ai/playground/search?q=starlette%20GitHub%20projects)

### aiohttp

[GitHub](https://github.com/aio-libs/aiohttp) · [PyPI](https://pypi.org/project/aiohttp) · [Docs](https://docs.aiohttp.org/en/stable/web_quickstart.html)

Serves and sends HTTP requests on asyncio.

- Downloads / mo: 562.2M
- Stars: 16.6K
- Last release: 3.14.5
- License: Apache-2.0 AND MIT
- Capabilities: [From the aiohttp docs](https://docs.aiohttp.org/en/stable/web_quickstart.html)

```sh
python -m pip install aiohttp==3.14.5
```

**home-assistant/core** (92.3K stars)

[home-assistant/core](https://github.com/home-assistant/core) 

```python
async def post(self, request: web.Request, entity_id: str) -> web.Response:
    """Update state of entity."""
    user: User = request[KEY_HASS_USER]
    if not user.is_admin:
        raise Unauthorized(entity_id=entity_id)
    hass = request.app[KEY_HASS]

    body = await request.text()

    try:
        data: Any = json_loads(body) if body else None
    except ValueError:
        return self.json_message("Invalid JSON specified.", HTTPStatus.BAD_REQUEST)

    if not isinstance(data, dict):
        return self.json_message(
            "State data should be a JSON object.", HTTPStatus.BAD_REQUEST
        )
    if (new_state := data.get("state")) is None:
        return self.json_message("No state specified.", HTTPStatus.BAD_REQUEST)

    attributes = data.get("attributes")
    force_update = data.get("force_update", False)

    is_new_state = hass.states.get(entity_id) is None

    # Write state
    try:
        hass.states.async_set(
            entity_id, new_state, attributes, force_update, self.context(request)
        )
    except InvalidEntityFormatError:
        return self.json_message(
            "Invalid entity ID specified.", HTTPStatus.BAD_REQUEST
        )
    except InvalidStateError:
        return self.json_message("Invalid state specified.", HTTPStatus.BAD_REQUEST)

    # Read the state back for our response
    status_code = HTTPStatus.CREATED if is_new_state else HTTPStatus.OK
    if (state := hass.states.get(entity_id)) is None:
        return self.json_message(
            "Error storing state.", HTTPStatus.INTERNAL_SERVER_ERROR
        )
    return web.Response(
        body=state.as_dict_json,
        content_type=CONTENT_TYPE_JSON,
        status=status_code,
        headers={"Location": f"/api/states/{entity_id}"},
    )
```

[homeassistant/components/api/__init__.py](https://github.com/home-assistant/core/blob/3df93331719fcb206ab24c165cadf1e796d52c02/homeassistant/components/api/__init__.py) · [More projects using aiohttp →](https://dashboard.exa.ai/playground/search?q=aiohttp%20GitHub%20projects)

**Quickstart**

```python
from aiohttp import web

routes = web.RouteTableDef()

@routes.get("/api/status")
async def status(request):
    return web.json_response({"message": "Hello"})

app = web.Application()
app.add_routes(routes)
web.run_app(app)

```

From [web_quickstart.html](https://docs.aiohttp.org/en/stable/web_quickstart.html)

### FastAPI

[GitHub](https://github.com/fastapi/fastapi) · [PyPI](https://pypi.org/project/fastapi) · [Docs](https://fastapi.tiangolo.com/tutorial/body/)

Builds Python APIs with typed request models and generated OpenAPI documentation.

- Downloads / mo: 544.0M
- Stars: 104.9K
- Last release: 0.165.0
- License: MIT
- Capabilities: [From the FastAPI docs](https://fastapi.tiangolo.com/tutorial/body/)

**Strengths**

- **Validates typed request bodies.** Declare models to parse and validate JSON request bodies.
- **Generates interactive API documentation.** Explore declared endpoints through the included Swagger UI.

**Watch out for**

- **Blocking libraries need sync handlers.** Use regular def when an I/O library cannot be awaited.

```sh
python -m pip install "fastapi[standard]==0.165.0"
```

**fastapi/full-stack-fastapi-template** (46.3K stars)

[fastapi/full-stack-fastapi-template](https://github.com/fastapi/full-stack-fastapi-template) 

```python
@router.post("/login/access-token")
def login_access_token(
    session: SessionDep, form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
) -> Token:
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = crud.authenticate(
        session=session, email=form_data.username, password=form_data.password
    )
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect email or password")
    elif not user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    return Token(
        access_token=security.create_access_token(
            user.id, expires_delta=access_token_expires
        )
    )

```

[backend/app/api/routes/login.py](https://github.com/fastapi/full-stack-fastapi-template/blob/aabb90126964a164e02aff39e7c385bb0598236d/backend/app/api/routes/login.py) · [More projects using FastAPI →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20fastapi%20for%20validated%20request%20handlers%2C%20application%20factories%20and%20serialized%20authentication%20responses&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from fastapi import FastAPI

app = FastAPI()

@app.get("/api/status")
async def status():
    return {"message": "Hello"}

```

From [body.md](https://fastapi.tiangolo.com/tutorial/body/)

### Flask

[GitHub](https://github.com/pallets/flask) · [PyPI](https://pypi.org/project/Flask) · [Docs](https://flask.palletsprojects.com/en/stable/api/)

Provides a compact web framework that can serve Python HTTP APIs.

- Downloads / mo: 208.0M
- Stars: 75.2K
- Last release: 3.1.3
- License: BSD-3-Clause
- Capabilities: [From the Flask docs](https://flask.palletsprojects.com/en/stable/api/)

**Strengths**

- **Returns JSON from dictionaries.** Return dictionaries or lists to create JSON responses.
- **Adds explicit API extensions.** Use flask-smorest, a REST extension, for validation, and OpenAPI generation.

**Watch out for**

- **Async views still occupy workers.** Each request ties up a worker, including an async view.
- **Spawned background tasks are cancelled.** Use a task queue instead of spawning work inside a view.

```sh
python -m pip install Flask==3.1.3
```

**apache/superset** (75.5K stars)

[apache/superset](https://github.com/apache/superset) 

```python
def create_app(
    superset_config_module: Optional[str] = None,
    superset_app_root: Optional[str] = None,
) -> Flask:
    app = SupersetApp(__name__)

    try:
        # Allow user to override our config completely
        config_module = superset_config_module or os.environ.get(
            "SUPERSET_CONFIG", "superset.config"
        )
        app.config.from_object(config_module)

        # Allow application to sit on a non-root path
        # *Please be advised that this feature is in BETA.*
        app_root = cast(
            str,
            superset_app_root
            or os.environ.get("SUPERSET_APP_ROOT")
            or app.config["APPLICATION_ROOT"],
        )
        # Normalize once at the source: a trailing slash ("/myapp/") would
        # otherwise leak into STATIC_ASSETS_PREFIX ("/myapp//static/...")
        # and APPLICATION_ROOT (the session-cookie path). The middlewares
        # below re-normalize defensively, but every consumer derives from
        # this value.
        app_root = app_root.rstrip("/") or "/"
        if app_root != "/":
            # If not set, manually configure options that depend on the
            # value of app_root so things work out of the box
            if not app.config["STATIC_ASSETS_PREFIX"]:
                app.config["STATIC_ASSETS_PREFIX"] = app_root
            # Prefix APP_ICON with the static assets prefix so the brand logo
            # resolves in subdirectory and CDN deployments alike. Using
            # STATIC_ASSETS_PREFIX (which defaults to app_root just above)
            # honours a custom CDN/static prefix when the operator sets one.
            if app.config.get("APP_ICON", "").startswith("/static/"):
                app.config["APP_ICON"] = (
                    f"{app.config['STATIC_ASSETS_PREFIX']}{app.config['APP_ICON']}"
                )
            if app.config["APPLICATION_ROOT"] == "/":
                app.config["APPLICATION_ROOT"] = app_root

        app_initializer = app.config.get("APP_INITIALIZER", SupersetAppInitializer)(app)
        app_initializer.init_app()

        # Must be applied before AppRootMiddleware so the path prefix
        # is stripped before the extension asset path regex runs.
        app.wsgi_app = ExtensionCacheMiddleware(app.wsgi_app)

        if app_root != "/":
            app.wsgi_app = AppRootMiddleware(app.wsgi_app, app_root)

        # Final WSGI wrap — must be outermost so it sees the raw inbound
        # PATH_INFO and 308s legacy `/superset/*` paths before any other
        # routing runs. Unconditional (independent of `app_root != "/"`)
        # because legacy bookmarks exist under root deployments too.
        # See the "Layering invariant" section of the module docstring
        # in `superset/middleware/legacy_prefix_redirect.py`.
        # mypy reads `app.wsgi_app` as `object` after the conditional
        # `AppRootMiddleware` rewrap above — the LUB of the two branches
        # widens it. The runtime type is always a WSGI callable; the
        # `# type: ignore` is intentional.
        app.wsgi_app = LegacyPrefixRedirectMiddleware(
            app.wsgi_app,  # type: ignore[arg-type]
            app_root,
        )

        # Set up LOCAL_EXTENSIONS file watcher when in debug mode
        if app.debug:
            start_local_extensions_watcher_thread(app)

        return app

    # Make sure that bootstrap errors ALWAYS get logged
    except Exception:
        logger.exception("Failed to create app")
        raise

```

[superset/app.py](https://github.com/apache/superset/blob/e60f79ffe2838cf0a543f906a4d5f1c6c4713652/superset/app.py) · [More projects using Flask →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20Flask%20for%20validated%20request%20handlers%2C%20application%20factories%20and%20serialized%20authentication%20responses&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from flask import Flask

app = Flask(__name__)

@app.get("/api/status")
def status():
    return {"message": "Hello"}

```

From [api.md](https://flask.palletsprojects.com/en/stable/api/)

### Tornado

[GitHub](https://github.com/tornadoweb/tornado) · [PyPI](https://pypi.org/project/tornado) · [Docs](https://www.tornadoweb.org/en/stable/web.html)

Provides a Python web framework and asynchronous networking library.

- Downloads / mo: 122.3M
- Stars: 22.2K
- Last release: 6.6.1
- License: Apache-2.0
- Capabilities: [From the Tornado docs](https://www.tornadoweb.org/en/stable/web.html)

```sh
python -m pip install tornado==6.6.1
```

**jupyter-server/jupyter_server** (573 stars)

[jupyter-server/jupyter_server](https://github.com/jupyter-server/jupyter_server) 

```python
@web.authenticated
@authorized
async def post(self):
    """Start a kernel."""
    km = self.kernel_manager
    model = self.get_json_body()
    if model is None:
        model = {"name": km.default_kernel_name}
    else:
        model.setdefault("name", km.default_kernel_name)

    kernel_id: str = await ensure_async(
        km.start_kernel(
            kernel_name=model["name"],
            path=model.get("path"),
            kernel_id=model.get("kernel_id"),
        )
    )
    model = await ensure_async(km.kernel_model(kernel_id))
    location = url_path_join(self.base_url, "api", "kernels", url_escape(kernel_id))
    self.set_header("Location", location)
    self.set_status(201)
    self.finish(json.dumps(model, default=json_default))
```

[jupyter_server/services/kernels/handlers.py](https://github.com/jupyter-server/jupyter_server/blob/c4c5a51d2cf77d31a266376582ee05c4d661ad4b/jupyter_server/services/kernels/handlers.py) · [More projects using Tornado →](https://dashboard.exa.ai/playground/search?q=tornado%20GitHub%20projects)

**Quickstart**

```python
import asyncio
import tornado.web

class StatusHandler(tornado.web.RequestHandler):
    def get(self):
        self.write({"message": "Hello"})

async def main():
    app = tornado.web.Application([(r"/api/status", StatusHandler)])
    app.listen(8888)
    await asyncio.Event().wait()

if __name__ == "__main__":
    asyncio.run(main())

```

From [web.html](https://www.tornadoweb.org/en/stable/web.html)

### Django

[GitHub](https://github.com/django/django) · [PyPI](https://pypi.org/project/Django) · [Docs](https://docs.djangoproject.com/en/6.1/ref/request-response/)

Provides a high-level Python web framework.

- Downloads / mo: 51.9M
- Stars: 91.8K
- Last release: 6.1.3
- License: BSD-3-Clause
- Capabilities: [From the Django docs](https://docs.djangoproject.com/en/6.1/ref/request-response/)

```sh
python -m pip install Django==6.1.3
```

**Quickstart**

```python
# demo/views.py
from django.http import JsonResponse

def status(request):
    return JsonResponse({"message": "Hello"})

# demo/urls.py
from django.urls import path
from .views import status

urlpatterns = [path("api/status", status)]

```

From [README.md](https://docs.djangoproject.com/en/6.1/ref/request-response/) · [Find projects using Django →](https://dashboard.exa.ai/playground/search?q=Django%20GitHub%20projects)

### Django REST framework

[GitHub](https://github.com/encode/django-rest-framework) · [PyPI](https://pypi.org/project/djangorestframework) · [Docs](https://www.django-rest-framework.org/api-guide/generic-views/)

Builds web APIs around Django models, serializers, and viewsets.

- Downloads / mo: 30.2M
- Stars: 30.2K
- Last release: 3.18.3
- License: BSD-3-Clause
- Capabilities: [From the Django REST framework docs](https://www.django-rest-framework.org/api-guide/generic-views/)

**Strengths**

- **Connects serializers and model views.** Build model-backed APIs with serializers, viewsets, and automatic routing.
- **Reports structured validation errors.** Call is_valid to validate data and inspect serializer errors.

**Watch out for**

- **Built-in schemas are deprecated.** Use drf-spectacular, an OpenAPI generator, for the recommended replacement.
- **Async path uses adrf.** Use adrf, an async adapter, for coroutine-based views.

```sh
python -m pip install djangorestframework==3.18.3 Django==6.1.3
```

**iMerica/dj-rest-auth** (1.9K stars)

[iMerica/dj-rest-auth](https://github.com/iMerica/dj-rest-auth) 

```python
def get_response(self):
    serializer_class = self.get_response_serializer()

    if api_settings.USE_JWT:
        from rest_framework_simplejwt.settings import (
            api_settings as jwt_settings,
        )
        access_token_expiration = (timezone.now() + jwt_settings.ACCESS_TOKEN_LIFETIME)
        refresh_token_expiration = (timezone.now() + jwt_settings.REFRESH_TOKEN_LIFETIME)
        return_expiration_times = api_settings.JWT_AUTH_RETURN_EXPIRATION
        auth_httponly = api_settings.JWT_AUTH_HTTPONLY

        data = {
            'user': self.user,
            'access': self.access_token,
        }

        if not auth_httponly:
            data['refresh'] = self.refresh_token
        else:
            # Wasnt sure if the serializer needed this
            data['refresh'] = ""

        if return_expiration_times:
            data['access_expiration'] = access_token_expiration
            data['refresh_expiration'] = refresh_token_expiration

        serializer = serializer_class(
            instance=data,
            context=self.get_serializer_context(),
        )
    elif self.token:
        serializer = serializer_class(
            instance=self.token,
            context=self.get_serializer_context(),
        )
    else:
        return Response(status=status.HTTP_204_NO_CONTENT)

    response = Response(serializer.data, status=status.HTTP_200_OK)
    if api_settings.USE_JWT:
        from .jwt_auth import set_jwt_cookies
        set_jwt_cookies(response, self.access_token, self.refresh_token)
    return response

```

[dj_rest_auth/views.py](https://github.com/iMerica/dj-rest-auth/blob/90082e3a4d257c053e5eef3f30f51cc7f55492ee/dj_rest_auth/views.py) · [More projects using Django REST framework →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20djangorestframework%20for%20validated%20request%20handlers%2C%20application%20factories%20and%20serialized%20authentication%20responses&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
# demo/settings.py: append to generated project settings
INSTALLED_APPS += ["rest_framework"]

# demo/views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(["GET"])
def status(request):
    return Response({"message": "Hello"})

# demo/urls.py
from django.urls import path
from .views import status

urlpatterns = [path("api/status", status)]

```

From [generic-views.md](https://www.django-rest-framework.org/api-guide/generic-views/)

### Bottle

[GitHub](https://github.com/bottlepy/bottle) · [PyPI](https://pypi.org/project/bottle) · [Docs](https://bottlepy.org/docs/0.13/tutorial.html)

Runs small web applications on WSGI.

- Downloads / mo: 9.6M
- Stars: 8.8K
- Last release: 0.13.4
- License: MIT
- Capabilities: [From the Bottle docs](https://bottlepy.org/docs/0.13/tutorial.html)

```sh
python -m pip install bottle==0.13.4
```

**Quickstart**

```python
from bottle import Bottle

app = Bottle()

@app.get("/api/status")
def status():
    return {"message": "Hello"}

app.run(host="127.0.0.1", port=8080)

```

From [tutorial.html](https://bottlepy.org/docs/0.13/tutorial.html) · [Find projects using Bottle →](https://dashboard.exa.ai/playground/search?q=bottle%20GitHub%20projects)

## FAQ

### Which Python REST API framework should I use?

[FastAPI](#fastapi) suits new APIs that declare request models with Pydantic and generate OpenAPI documentation. [Django REST framework](#django-rest-framework) suits Django projects that need serializers, generic views, and authentication. [Flask](#flask) suits small services with explicit routes.

### What is aiohttp?

[aiohttp](#aiohttp) is an asyncio HTTP framework with a web server and a separate HTTP client in one package.

### What is Django REST framework?

[Django REST framework](#django-rest-framework) adds API serializers, parsers, generic views, authentication, and response rendering to Django.

### Flask vs Django: which should I use?

[Flask](#flask) is a WSGI microframework that keeps routes and request handling explicit. [Django](#django) is a full application framework with an ORM, authentication, and generic views.

### FastAPI vs Flask: which should I use?

[FastAPI](#fastapi) is an ASGI framework that validates requests against declared Pydantic models and generates OpenAPI documentation. [Flask](#flask) is a WSGI microframework whose async views stay inside the WSGI worker lifecycle.

### What is Starlette?

[Starlette](#starlette) is a low-level ASGI toolkit with routing, request and response objects, middleware, and async endpoints.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python REST API libraries FastAPI Flask Django REST framework Falcon code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
