Seven Alternatives To FastAPI To Explore and Contribute To | Python

First of all, there is nothing wrong with FastAPI. FastAPI is a good web framework. I have used it many times in my hobby projects and works fine.

This article is about the alternatives of FastAPI for anyone who wants to try another web framework, for the sake of exploring a new software. To anyone who finds joy in trying new things or different things. Also, if you want to contribute to Open Source Software and you are interested in web frameworks.

Also, this is a biased article, because in the list below are seven Python web frameworks that we can use as FastAPI alternatives, and I'm excluding from this list Flask and Django. Not because they are bad, but because I think they are well known.

Robyn

Robyn is a fast async Python web framework coupled with a web server written in Rust.

Features:

  • Authentication and Authorization

  • Middlewares

  • CORS

  • WebSockets

  • Subrouters

  • Views

  • Templating with Jinja2

Example:

pip install robyn

We create the app.py file and paste the following code.

from robyn import Robyn

app = Robyn(__file__)

@app.get("/")
async def h(request):
    return "Hello, world!"

app.start(port=8080)

Then, we run the following command in the console:

python3 app.py

Documentation

Repository

Discord

Blacksheep

BlackSheep is an asynchronous web framework for building event-based web applications with Python. It is inspired by Flask, ASP.NET Core, and the work of Yury Selivanov.

It has a similar syntax as FastAPI and also it could be used with Uvicorn. As the documentation says, it has been tested to use Hypercorn as an ASGI HTTP server too.

According to its documentation, BlackSheep offers:

  • A rich code API, based on dependency injection and inspired by Flask and ASP.NET Core

  • A typing-friendly codebase, which enables a comfortable development experience thanks to hints when coding with IDEs

  • Built-in generation of OpenAPI Documentation, supporting version 3, YAML, and JSON

  • A cross-platform framework, using the most modern versions of Python

  • Good performance

Example:

pip install blacksheep uvicorn

Create the server.py file and paste the following code:

from datetime import datetime
from blacksheep import Application


app = Application()

@app.route("/")
def home():
    return f"Hello, World! {datetime.utcnow().isoformat()}"

Then, we run the following command in the console:

uvicorn server:app --port 44777 --reload

Documentation

Repository

Gitter

LiteStar

Litestar is a powerful, flexible, highly performant, and opinionated ASGI framework.

The Litestar framework supports:

  • Plugins

  • Ships with dependency injection

  • Security primitives

  • OpenAPI schema generation

  • MessagePack, middlewares

  • A great CLI experience

Example:

pip install litestar[standard]

We create the app.py file and paste the following code:

from litestar import Litestar, get


@get("/")
async def index() -> str:
    return "Hello, world!"


@get("/books/{book_id:int}")
async def get_book(book_id: int) -> dict[str, int]:
    return {"book_id": book_id}


app = Litestar([index, get_book])

Then, we run the following command in the console:

litestar run
# Or you can run Uvicorn directly:
uvicorn app:app --reload

Documentation

Repository

Discord

Sanic

Sanic is a Python 3.8+ web server and web framework that’s written to go fast. It allows the usage of the async/await syntax added in Python 3.5, which makes your code non-blocking and speedy.

Sanic intentionally aims for a clean and unopinionated feature list. The project does not want to require you to build your application in a certain way and tries to avoid prescribing specific development patterns. Several third-party plugins are built and maintained by the community to add additional features that do not otherwise meet the requirements of the core repository.

However, to help API developers, the Sanic organization maintains an official plugin called Sanic Extensions to provide all sorts of goodies, including:

  • OpenAPI documentation with Redoc and/or Swagger

  • CORS protection

  • Dependency injection into route handlers

  • Request query arguments and body input validation

  • Auto create HEAD, OPTIONS, and TRACE endpoints

  • Predefined, endpoint-specific response serializers

Example:

pip install sanic

We create the server.py file and paste the following content:

from sanic import Sanic
from sanic.response import text

app = Sanic("MyHelloWorldApp")

@app.get("/")
async def hello_world(request):
    return text("Hello, world.")

Then, we run the following command in the console:

sanic server

Documentation

Repository

Discord

Falcon

Falcon is a reliable, high-performance Python web framework for building large-scale app backends and microservices. It works with any WSGI server, encourages the REST architectural style, and tries to do as little as possible while remaining highly effective.

Falcon tries to do as little as possible while remaining highly effective.

  • ASGI, WSGI, and WebSocket support

  • Native asyncio support

  • No reliance on magic globals for routing and state management

  • Stable interfaces with an emphasis on backwards-compatibility

  • Simple API modeling through centralized RESTful routing

  • Highly-optimized, extensible code base

  • Easy access to headers and bodies through request and response objects

  • DRY request processing via middleware components and hooks

  • Strict adherence to RFCs

  • Idiomatic HTTP error responses

  • Straightforward exception handling

  • Snappy testing with WSGI/ASGI helpers and mocks

  • CPython 3.5+ and PyPy 3.5+ support

Example:

pip install falcon, uvicorn

We create a server.py file and paste the content:

import falcon
import falcon.asgi


# Falcon follows the REST architectural style, meaning (among
# other things) that you think in terms of resources and state
# transitions, which map to HTTP verbs.
class ThingsResource:
    async def on_get(self, req, resp):
        """Handles GET requests"""
        resp.status = falcon.HTTP_200  # This is the default status
        resp.content_type = falcon.MEDIA_TEXT  # Default is JSON, so override
        resp.text = (
            '\nTwo things awe me most, the starry sky '
            'above me and the moral law within me.\n'
            '\n'
            '    ~ Immanuel Kant\n\n'
        )


# falcon.asgi.App instances are callable ASGI apps...
# in larger applications the app is created in a separate file
app = falcon.asgi.App()

# Resources are represented by long-lived class instances
things = ThingsResource()

# things will handle all requests to the '/things' URL path
app.add_route('/things', things)

Then, we run the following command in the console:

uvicorn server:app

Documentation

Repository

Emmett

Emmett is a full-stack Python web framework designed with simplicity in mind.

Emmett aims to be understandable, easy to learn and to be used, so you can focus completely on your product's features.

Features:

  • Routing system

  • Templating system

  • Websockets

  • Validations

  • Forms generations

  • Sesions

  • Authorization system

  • Caching

  • ORM

Example:

pip install emmett

We create an app.py file and paste the following code:

from emmett import App

app = App(__name__)

@app.route("/")
async def hello():
    return "Hello world!"

Then, we run the following command in the console:

emmett develop

Documentation

Repository

Starlette

Starlette is a lightweight ASGI framework/toolkit, which is ideal for building async web services in Python.

It gives you the following features:

  • A lightweight, low-complexity HTTP web framework.

  • WebSocket support.

  • In-process background tasks.

  • Startup and shutdown events.

  • Test client built on httpx.

  • CORS, GZip, Static Files, Streaming responses.

  • Session and Cookie support.

  • 100% test coverage.

  • 100% type annotated codebase.

  • Few hard dependencies.

  • Compatible with asyncio and trio backends.

Example:

pip install starlette uvicorn

We create a server.py file and paste the following code:

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


async def homepage(request):
    return JSONResponse({'hello': 'world'})

routes = [
    Route("/", endpoint=homepage)
]

app = Starlette(debug=True, routes=routes)

Then, we run the following command in the console:

uvicorn server:app

Documentation

Repository

Conclusion

In this article, we explored seven web frameworks for people who are willing to try something different from FastAPI. Many of them have a similar syntax and make it easy to use for people who are used to using FastAPI or Flask.

Thank you for taking the time to read this article.

If you have any recommendations about other packages, architectures, how to improve my code, my English, or anything; please leave a comment or contact me through Twitter, or LinkedIn.

Resources

Robyn Documentation

Robyn Github Page

Sanic Documentation

Blacksheep Documentation

LiteStar Documentation

Starlette Documentation

Falcon Documentation

Emmett Documentation

0
Subscribe to my newsletter

Read articles from Carlos Armando Marcano Vargas directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Carlos Armando Marcano Vargas
Carlos Armando Marcano Vargas

I am a backend developer from Venezuela. I enjoy writing tutorials for open source projects I using and find interesting. Mostly I write tutorials about Python, Go, and Rust.