alternatives.md
This file
Path
docs/alternatives.md
417 lines · 22.9 KiB · Markdown
Last changed by
:memo: Add first version of docsSebastián Ramírezbefore adoptionc24269f
History of this fileTake it
:memo: Add first version of docsSebastián Ramírezbefore adoptionc24269f
lines 1–417why, one step back1What inspired **Typer**, how it compares to other alternatives and what it learned from them.23Coming soon...45<!-- ## Intro67**FastAPI** wouldn't exist if not for the previous work of others.89There have been many tools created before that have helped inspire its creation.1011I have been avoiding the creation of a new framework for several years. First I tried to solve all the features covered by **FastAPI** using many different frameworks, plug-ins, and tools.1213But at some point, there was no other option than creating something that provided all these features, taking the best ideas from previous tools, and combining them in the best way possible, using language features that weren't even available before (Python 3.6+ type hints).1415## Previous tools1617### <a href="https://www.djangoproject.com/" target="_blank">Django</a>1819It's the most popular Python framework and is widely trusted. It is used to build systems like Instagram.2021It's relatively tightly coupled with relational databases (like MySQL or PostgreSQL), so, having a NoSQL database (like Couchbase, MongoDB, Cassandra, etc) as the main store engine is not very easy.2223It was created to generate the HTML in the backend, not to create APIs used by a modern frontend (like React, Vue.js and Angular) or by other systems (like <abbr title="Internet of Things">IoT</abbr> devices) communicating with it.2425### <a href="https://www.django-rest-framework.org/" target="_blank">Django REST Framework</a>2627Django REST framework was created to be a flexible toolkit for building Web APIs using Django underneath, to improve its API capabilities.2829It is used by many companies including Mozilla, Red Hat and Eventbrite.3031It was one of the first examples of **automatic API documentation**, and this was specifically one of the first ideas that inspired "the search for" **FastAPI**.3233!!! note34 Django REST Framework was created by Tom Christie. The same creator of Starlette and Uvicorn, on which **FastAPI** is based.353637!!! check "Inspired **FastAPI** to"38 Have an automatic API documentation web user interface.3940### <a href="http://flask.pocoo.org/" target="_blank">Flask</a>4142Flask is a "microframework", it doesn't include database integrations nor many of the things that come by default in Django.4344This simplicity and flexibility allow doing things like using NoSQL databases as the main data storage system.4546As it is very simple, it's relatively intuitive to learn, although the documentation gets somewhat technical at some points.4748It is also commonly used for other applications that don't necessarily need a database, user management, or any of the many features that come pre-built in Django. Although many of these features can be added with plug-ins.4950This decoupling of parts, and being a "microframework" that could be extended to cover exactly what is needed was a key feature that I wanted to keep.5152Given the simplicity of Flask, it seemed like a good match for building APIs. The next thing to find was a "Django REST Framework" for Flask.5354!!! check "Inspired **FastAPI** to"55 Be a micro-framework. Making it easy to mix and match the tools and parts needed.5657 Have a simple and easy to use routing system.585960### <a href="http://docs.python-requests.org" target="_blank">Requests</a>6162**FastAPI** is not actually an alternative to **Requests**. Their scope is very different.6364It would actually be common to use Requests *inside* of a FastAPI application.6566But still, FastAPI got quite some inspiration from Requests.6768**Requests** is a library to *interact* with APIs (as a client), while **FastAPI** is a library to *build* APIs (as a server).6970They are, more or less, at opposite ends, complementing each other.7172Requests has a very simple and intuitive design, it's very easy to use, with sensible defaults. But at the same time, it's very powerful and customizable.7374That's why, as said in the official website:7576> Requests is one of the most downloaded Python packages of all time7778The way you use it is very simple. For example, to do a `GET` request, you would write:7980```Python81response = requests.get("http://example.com/some/url")82```8384The FastAPI counterpart API path operation could look like:8586```Python hl_lines="1"87@app.get("/some/url")88def read_url():89 return {"message": "Hello World"}90```9192See the similarities in `requests.get(...)` and `@app.get(...)`.9394!!! check "Inspired **FastAPI** to"95 * Have a simple and intuitive API.96 * Use HTTP method names (operations) directly, in a straightforward and intuitive way.97 * Have sensible defaults, but powerful customizations.9899100### <a href="https://swagger.io/" target="_blank">Swagger</a> / <a href="https://github.com/OAI/OpenAPI-Specification/" target="_blank">OpenAPI</a>101102The main feature I wanted from Django REST Framework was the automatic API documentation.103104Then I found that there was a standard to document APIs, using JSON (or YAML, an extension of JSON) called Swagger.105106And there was a web user interface for Swagger APIs already created. So, being able to generate Swagger documentation for an API would allow using this web user interface automatically.107108At some point, Swagger was given to the Linux Foundation, to be renamed OpenAPI.109110That's why when talking about version 2.0 it's common to say "Swagger", and for version 3+ "OpenAPI".111112!!! check "Inspired **FastAPI** to"113 Adopt and use an open standard for API specifications, instead of a custom schema.114115 And integrate standards-based user interface tools:116117 * <a href="https://github.com/swagger-api/swagger-ui" target="_blank">Swagger UI</a>118 * <a href="https://github.com/Rebilly/ReDoc" target="_blank">ReDoc</a>119120 These two were chosen for being fairly popular and stable, but doing a quick search, you could find dozens of additional alternative user interfaces for OpenAPI (that you can use with **FastAPI**).121122### Flask REST frameworks123124There are several Flask REST frameworks, but after investing the time and work into investigating them, I found that many are discontinued or abandoned, with several standing issues that made them unfit.125126### <a href="https://marshmallow.readthedocs.io/en/3.0/" target="_blank">Marshmallow</a>127128One of the main features needed by API systems is data "<abbr title="also called marshalling, conversion">serialization</abbr>" which is taking data from the code (Python) and converting it into something that can be sent through the network. For example, converting an object containing data from a database into a JSON object. Converting `datetime` objects into strings, etc.129130Another big feature needed by APIs is data validation, making sure that the data is valid, given certain parameters. For example, that some field is an `int`, and not some random string. This is especially useful for incoming data.131132Without a data validation system, you would have to do all the checks by hand, in code.133134These features are what Marshmallow was built to provide. It is a great library, and I have used it a lot before.135136But it was created before there existed Python type hints. So, to define every <abbr title="the definition of how data should be formed">schema</abbr> you need to use specific utils and classes provided by Marshmallow.137138!!! check "Inspired **FastAPI** to"139 Use code to define "schemas" that provide data types and validation, automatically.140141### <a href="https://webargs.readthedocs.io/en/latest/" target="_blank">Webargs</a>142143Another big feature required by APIs is <abbr title="reading and converting to Python data">parsing</abbr> data from incoming requests.144145Webargs is a tool that was made to provide that on top of several frameworks, including Flask.146147It uses Marshmallow underneath to do the data validation. And it was created by the same developers.148149It's a great tool and I have used it a lot too, before having **FastAPI**.150151!!! info152 Webargs was created by the same Marshmallow developers.153154!!! check "Inspired **FastAPI** to"155 Have automatic validation of incoming request data.156157### <a href="https://apispec.readthedocs.io/en/stable/" target="_blank">APISpec</a>158159Marshmallow and Webargs provide validation, parsing and serialization as plug-ins.160161But documentation is still missing. Then APISpec was created.162163It is a plug-in for many frameworks (and there's a plug-in for Starlette too).164165The way it works is that you write the definition of the schema using YAML format inside the docstring of each function handling a route.166167And it generates OpenAPI schemas.168169That's how it works in Flask, Starlette, Responder, etc.170171But then, we have again the problem of having a micro-syntax, inside of a Python string (a big YAML).172173The editor can't help much with that. And if we modify parameters or Marshmallow schemas and forget to also modify that YAML docstring, the generated schema would be obsolete.174175!!! info176 APISpec was created by the same Marshmallow developers.177178179!!! check "Inspired **FastAPI** to"180 Support the open standard for APIs, OpenAPI.181182### <a href="https://flask-apispec.readthedocs.io/en/latest/" target="_blank">Flask-apispec</a>183184It's a Flask plug-in, that ties together Webargs, Marshmallow and APISpec.185186It uses the information from Webargs and Marshmallow to automatically generate OpenAPI schemas, using APISpec.187188It's a great tool, very under-rated. It should be way more popular than many Flask plug-ins out there. It might be due to its documentation being too concise and abstract.189190This solved having to write YAML (another syntax) inside of Python docstrings.191192This combination of Flask, Flask-apispec with Marshmallow and Webargs was my favorite backend stack until building **FastAPI**.193194Using it led to the creation of several Flask full-stack generators. These are the main stack I (and several external teams) have been using up to now:195196* <a href="https://github.com/tiangolo/full-stack" target="_blank">https://github.com/tiangolo/full-stack</a>197* <a href="https://github.com/tiangolo/full-stack-flask-couchbase" target="_blank">https://github.com/tiangolo/full-stack-flask-couchbase</a>198* <a href="https://github.com/tiangolo/full-stack-flask-couchdb" target="_blank">https://github.com/tiangolo/full-stack-flask-couchdb</a>199200And these same full-stack generators were the base of the <a href="/project-generation/" target="_blank">**FastAPI** project generator</a>.201202!!! info203 Flask-apispec was created by the same Marshmallow developers.204205!!! check "Inspired **FastAPI** to"206 Generate the OpenAPI schema automatically, from the same code that defines serialization and validation.207208### <a href="https://nestjs.com/" target="_blank">NestJS</a> (and <a href="https://angular.io/" target="_blank">Angular</a>)209210This isn't even Python, NestJS is a JavaScript (TypeScript) NodeJS framework inspired by Angular.211212It achieves something somewhat similar to what can be done with Flask-apispec.213214It has an integrated dependency injection system, inspired by Angular two. It requires pre-registering the "injectables" (like all the other dependency injection systems I know), so, it adds to the verbosity and code repetition.215216As the parameters are described with TypeScript types (similar to Python type hints), editor support is quite good.217218But as TypeScript data is not preserved after compilation to JavaScript, it cannot rely on the types to define validation, serialization and documentation at the same time. Due to this and some design decisions, to get validation, serialization and automatic schema generation, it's needed to add decorators in many places. So, it becomes quite verbose.219220It can't handle nested models very well. So, if the JSON body in the request is a JSON object that has inner fields that in turn are nested JSON objects, it cannot be properly documented and validated.221222!!! check "Inspired **FastAPI** to"223 Use Python types to have great editor support.224225 Have a powerful dependency injection system. Find a way to minimize code repetition.226227### <a href="https://sanic.readthedocs.io/en/latest/" target="_blank">Sanic</a>228229It was one of the first extremely fast Python frameworks based on `asyncio`. It was made to be very similar to Flask.230231!!! note "Technical Details"232 It used <a href="https://github.com/MagicStack/uvloop" target="_blank">`uvloop`</a> instead of the default Python `asyncio` loop. That's what made it so fast.233234 It <a href="https://github.com/huge-success/sanic/issues/761" target="_blank">still doesn't implement the ASGI spec for Python asynchronous web development</a>, but it clearly inspired Uvicorn and Starlette, that are currently faster than Sanic in open benchmarks.235236!!! check "Inspired **FastAPI** to"237 Find a way to have a crazy performance.238 239 That's why **FastAPI** is based on Starlette, as it is the fastest framework available (tested by third-party benchmarks).240241### <a href="https://falconframework.org/" target="_blank">Falcon</a>242243Falcon is another high performance Python framework, it is designed to be minimal, and work as the foundation of other frameworks like Hug.244245It uses the previous standard for Python web frameworks (WSGI) which is synchronous, so it can't handle WebSockets and other use cases. Nevertheless, it also has a very good performance.246247It is designed to have functions that receive two parameters, one "request" and one "response". Then you "read" parts from the request, and "write" parts to the response. Because of this design, it is not possible to declare request parameters and bodies with standard Python type hints as function parameters.248249So, data validation, serialization, and documentation, have to be done in code, not automatically. Or they have to be implemented as a framework on top of Falcon, like Hug. This same distinction happens in other frameworks that are inspired by Falcon's design, of having one request object and one response object as parameters.250251!!! check "Inspired **FastAPI** to"252 Find ways to get great performance.253254 Along with Hug (as Hug is based on Falcon) inspired **FastAPI** to declare a `response` parameter in functions.255256 Although in FastAPI it's optional, and is used mainly to set headers, cookies, and alternative status codes.257258### <a href="https://moltenframework.com/" target="_blank">Molten</a>259260I discovered Molten in the first stages of building **FastAPI**. And it has quite similar ideas:261262* Based on Python type hints.263* Validation and documentation from these types.264* Dependency Injection system.265266It doesn't use a data validation, serialization and documentation third-party library like Pydantic, it has its own. So, these data type definitions would not be reusable as easily.267268It requires a little bit more verbose configurations. And as it is based on WSGI (instead of ASGI), it is not designed to take advantage of the high-performance provided by tools like Uvicorn, Starlette and Sanic.269270The dependency injection system requires pre-registration of the dependencies and the dependencies are solved based on the declared types. So, it's not possible to declare more than one "component" that provides a certain type.271272Routes are declared in a single place, using functions declared in other places (instead of using decorators that can be placed right on top of the function that handles the endpoint). This is closer to how Django does it than to how Flask (and Starlette) does it. It separates in the code things that are relatively tightly coupled.273274!!! check "Inspired **FastAPI** to"275 Define extra validations for data types using the "default" value of model attributes. This improves editor support, and it was not available in Pydantic before.276277 This actually inspired updating parts of Pydantic, to support the same validation declaration style (all this functionality is now already available in Pydantic).278279### <a href="http://www.hug.rest/" target="_blank">Hug</a>280281Hug was one of the first frameworks to implement the declaration of API parameter types using Python type hints. This was a great idea that inspired other tools to do the same.282283It used custom types in its declarations instead of standard Python types, but it was still a huge step forward.284285It also was one of the first frameworks to generate a custom schema declaring the whole API in JSON.286287It was not based on a standard like OpenAPI and JSON Schema. So it wouldn't be straightforward to integrate it with other tools, like Swagger UI. But again, it was a very innovative idea.288289It has an interesting, uncommon feature: using the same framework, it's possible to create APIs and also CLIs.290291As it is based on the previous standard for synchronous Python web frameworks (WSGI), it can't handle Websockets and other things, although it still has high performance too.292293!!! info294 Hug was created by Timothy Crosley, the same creator of <a href="https://github.com/timothycrosley/isort" target="_blank">`isort`</a>, a great tool to automatically sort imports in Python files.295296!!! check "Ideas inspired in **FastAPI**"297 Hug inspired parts of APIStar, and was one of the tools I found most promising, alongside APIStar.298299 Hug helped inspiring **FastAPI** to use Python type hints to declare parameters, and to generate a schema defining the API automatically.300301 Hug inspired **FastAPI** to declare a `response` parameter in functions to set headers and cookies.302303### <a href="https://github.com/encode/apistar" target="_blank">APIStar</a> (<= 0.5)304305Right before deciding to build **FastAPI** I found **APIStar** server. It had almost everything I was looking for and had a great design.306307It was one of the first implementations of a framework using Python type hints to declare parameters and requests that I ever saw (before NestJS and Molten). I found it more or less at the same time as Hug. But APIStar used the OpenAPI standard.308309It had automatic data validation, data serialization and OpenAPI schema generation based on the same type hints in several places.310311Body schema definitions didn't use the same Python type hints like Pydantic, it was a bit more similar to Marshmallow, so, editor support wouldn't be as good, but still, APIStar was the best available option.312313It had the best performance benchmarks at the time (only surpassed by Starlette).314315At first, it didn't have an automatic API documentation web UI, but I knew I could add Swagger UI to it.316317It had a dependency injection system. It required pre-registration of components, as other tools discussed above. But still, it was a great feature.318319I was never able to use it in a full project, as it didn't have security integration, so, I couldn't replace all the features I was having with the full-stack generators based on Flask-apispec. I had in my backlog of projects to create a pull request adding that functionality.320321But then, the project's focus shifted.322323It was no longer an API web framework, as the creator needed to focus on Starlette.324325Now APIStar is a set of tools to validate OpenAPI specifications, not a web framework.326327!!! info328 APIStar was created by Tom Christie. The same guy that created:329330 * Django REST Framework331 * Starlette (in which **FastAPI** is based)332 * Uvicorn (used by Starlette and **FastAPI**)333334!!! check "Inspired **FastAPI** to"335 Exist.336337 The idea of declaring multiple things (data validation, serialization and documentation) with the same Python types, that at the same time provided great editor support, was something I considered a brilliant idea.338 339 And after searching for a long time for a similar framework and testing many different alternatives, APIStar was the best option available.340341 Then APIStar stopped to exist as a server and Starlette was created, and was a new better foundation for such a system. That was the final inspiration to build **FastAPI**.342343 I consider **FastAPI** a "spiritual successor" to APIStar, while improving and increasing the features, typing system, and other parts, based on the learnings from all these previous tools.344345## Used by **FastAPI**346347### <a href="https://pydantic-docs.helpmanual.io/" target="_blank">Pydantic</a>348349Pydantic is a library to define data validation, serialization and documentation (using JSON Schema) based on Python type hints.350351That makes it extremely intuitive.352353It is comparable to Marshmallow. Although it's faster than Marshmallow in benchmarks. And as it is based on the same Python type hints, the editor support is great.354355!!! check "**FastAPI** uses it to"356 Handle all the data validation, data serialization and automatic model documentation (based on JSON Schema).357358 **FastAPI** then takes that JSON Schema data and puts it in OpenAPI, apart from all the other things it does.359360### <a href="https://www.starlette.io/" target="_blank">Starlette</a>361362Starlette is a lightweight <abbr title="The new standard for building asynchronous Python web">ASGI</abbr> framework/toolkit, which is ideal for building high-performance asyncio services.363364It is very simple and intuitive. It's designed to be easily extensible, and have modular components.365366It has:367368* Seriously impressive performance.369* WebSocket support.370* GraphQL support.371* In-process background tasks.372* Startup and shutdown events.373* Test client built on requests.374* CORS, GZip, Static Files, Streaming responses.375* Session and Cookie support.376* 100% test coverage.377* 100% type annotated codebase.378* Zero hard dependencies.379380Starlette is currently the fastest Python framework tested. Only surpassed by Uvicorn, which is not a framework, but a server.381382Starlette provides all the basic web microframework functionality.383384But it doesn't provide automatic data validation, serialization or documentation.385386That's one of the main things that **FastAPI** adds on top, all based on Python type hints (using Pydantic). That, plus the dependency injection system, security utilities, OpenAPI schema generation, etc.387388!!! note "Technical Details"389 ASGI is a new "standard" being developed by Django core team members. It is still not a "Python standard" (a PEP), although they are in the process of doing that.390391 Nevertheless, it is already being used as a "standard" by several tools. This greatly improves interoperability, as you could switch Uvicorn for any other ASGI server (like Daphne or Hypercorn), or you could add ASGI compatible tools, like `python-socketio`.392393!!! check "**FastAPI** uses it to"394 Handle all the core web parts. Adding features on top.395396 The class `FastAPI` itself inherits directly from the class `Starlette`.397 398 So, anything that you can do with Starlette, you can do it directly with **FastAPI**, as it is basically Starlette on steroids.399400### <a href="https://www.uvicorn.org/" target="_blank">Uvicorn</a>401402Uvicorn is a lightning-fast ASGI server, built on uvloop and httptools.403404It is not a web framework, but a server. For example, it doesn't provide tools for routing by paths. That's something that a framework like Starlette (or **FastAPI**) would provide on top.405406It is the recommended server for Starlette and **FastAPI**.407408!!! check "**FastAPI** recommends it as"409 The main web server to run **FastAPI** applications.410411 You can combine it with Gunicorn, to have an asynchronous multi-process server.412413 Check more details in the <a href="/deployment/" target="_blank">Deployment</a> section.414415## Benchmarks and speed416417To understand, compare, and see the difference between Uvicorn, Starlette and FastAPI, check the section about [Benchmarks](/benchmarks/). -->