FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+. It is one of the fastest Python frameworks available, as measured by independent benchmarks.
It is based on standard Python type hints. Using them, you get automatic data validation, serialization, and documentation. Including deeply nested JSON documents. And you get editor completion and checks everywhere.
Designed around the OpenAPI (Swagger) and JSON Schema standards.
It includes 2 alternative interactive API documentation systems that are generated automatically.
OAuth2 capable from the start (including JWT). Dependency Injection system, compatible with all databases (relational and NoSQL), Websockets, GraphQL, CORS, etc.
Do you have any examples of a good project layout? How do I have multiple controllers, large numbers of models, etc. There's very little in the way of "just a restful backend" templates in Python.
Another way to get Go like speed is to use Go. Go has an excellent built in http web server, and unlike Python it comes standard with a bug reducing type system and an easy and intuitive syntax. In fact, the entire specification of the language can be read in an hour by a novice programmer.
Not only that, but Go has best in class editing support in VSCode and Vim, has an official code formatting tool (sorry black), and makes writing concurrent code painless with a syncronous abstraction (sorry asyncio).
Also it may have good response times in a vacuum but there’s still the Python memory tax, startup times (which matter when you need to scale horizontally), and scaling of latency to think about.
Python is a hugely productive language. That's the benefit.
We're building out an async ecosystem here that makes it way more performance-competitive with Node and Go.
For a lot of folks it's going to hit a sweet spot of developer productivity plus ability to scale up hugely. That's a big deal.
Doesn't mean you have to use it, but there's no need to neg on the great work folks are doing in this space just because Python's not your preferred language of choice.
Yeah, the advantage here over Go would be to have automatic data validation, serialization, and documentation, all based on standards: OpenAPI and JSON Schema. Including automatic web user interface for API documentation.
And maybe the dependency injection system.
And Python's ecosystem with lots of packages.
And that Python is the best/main way to do Machine Learning/Deep Learning.
I personally don't think new asyncio (Python 3.6) is more difficult, but that's more personal taste.
Indeed, FastAPI inherited benefits from ideas in Go and other languages and frameworks.
> Yeah, the advantage here over Go would be to have automatic data validation, serialization, and documentation, all based on standards: OpenAPI and JSON Schema. Including automatic web user interface for API documentation.
Golang has libraries for all of the things you mentioned, and web tools to generate APIs based on those schemas. There's no advantage here over Go.
> And maybe the dependency injection system.
Go has interfaces, which facilitates easy DI. No advantage there, and Go sells itself on not having a magic DI framework like the crap Angular 1 had.
> And Python's ecosystem with lots of packages.
Python's ecosystem may have more packages taken as a whole, but Go has a richer web and infrastructure community thanks to being a web first language and growing out of the DevOps community.
> And that Python is the best/main way to do Machine Learning/Deep Learning.
Which means nothing. You shouldn't be running ML in your web server. You use grpc or http to make requests to your ML backend, or generate a config for the web server to consume.
> I personally don't think new asyncio (Python 3.6) is more difficult, but that's more personal taste.
Even if it isn't more difficult, functions have to be colored async which leads to ecosystem fragmentation. It's a huge pita.
It looks like some (extremely dedicated) trolling, don't take it seriously. There is certainly nothing wrong in expanding the ecosystem of your preferred language!
Languages aren't flavors of ice cream. Considering the technical arguments of one technology over the other is part and parcel of our profession, and online forums are we go to have these discussions. The person who wrote this, or the people who might look to consume it might not know that better alternatives exist that can meet their requirements and offer them additional advantages.
> Golang has libraries for all of the things you mentioned, and web tools to generate APIs based on those schemas. [...]
Would you cite some? I would love to see the links, packages, etc. And how could you achieve the same in Go:
Having a single type declaration, get web data validation, serialization, documentation with OpenAPI and automatic clear error responses.
I would love to see it, because before building FastAPI I looked for it in Go-land a lot too, and didn't find it, not even closer to the tools that already existed in Python.
You should also check out starlette and other supporting projects that Tom Christie (of DRF fame) is working on right now. Both FastAPI and Responder are thin wrappers around starlette.
Tom Christie has been quietly building what's starting to look like an async first decoupled version of django:
Yes, most of the tests come directly from the docs, that way, by having full test coverage, means that at least a big part of the functionality is not only tested but also documented somewhere.
Looks great; been searching for something to rewrite a 6yo side-project with and this looks just about perfect.
Small wrinkle: I spotted a broken link on the "deployment" page - "Bigger applications with multiple files" doesn't link to the right place (in fact it links nowhere, the `href` attribute has no value).
How does this compare to https://moltenframework.com/? They both provide type hints and are inspired by API Star. Why should I use FastAPI over molten?
Molten also helped inspire parts of FastAPI. And they are indeed quite similar in several things.
Molten is based on WSGI, FastAPI is based on ASGI.
So, you can do async/await stuff in FastAPI.
FastAPI inherits directly form Starlette, so it inherits its benefits, like testing tools, GraphQL in-process background tasks, etc.
And it benefits from the ASGI ecosystem, for example with plugins to handle Django-Channels like Websockets, deployment to "serverless", even including other tools like Socket-IO.
FastAPI is based on Pydantic instead of an internal library for declaring schemas, so any improvements there are inherited here.
It supports Flask like route decorators.
The dependency injection is simpler, probably more intuitive (but this is more subjective). The same with several other parts.
But again, Molten is a great tool, and was one of the tools that inspired FastAPI (it's even mentioned in the docs).
It's designed to be very helpful while building web APIs that communicate JSON over HTTP.
You can have semi-automatic data validation, serialization (converting from JSON to Python data types, etc). And an automatic web user interface that documents your API. You don't have to do anything to have that web interface, it's done automatically from your definitions of the data types that you need.
It is also compatible with Jinja templates.
It's like a modern Flask with several benefits, especially for web APIs.
> C library everywhere ( network, serialization ... )
I view this as a strong benefit in python. Write your app, and if you need to really squeeze performance in some critical area, writing a C/C++ extension is simple enough.
Maybe, but Python is still quite easy to pick, the only one that can do Deep Learning and Machine Learning well, etc.
So, if we can use it, take advantage of its benefits and have tools like this that simplify everything without too many constraints, I would say it's a good tradeoff.
Yeah for data science and CRUD workloads python is great. The performance difference between go and python in those settings are negligible and python wins out on ease of use and ecosystem.
>Maybe, but Python is still quite easy to pick, the only one that can do Deep Learning and Machine Learning well, etc.
This is such a terrible state of affairs. There are so many times I've wanted to generate synthetic training data efficiently and iterate in a tight training loop where I've gone back and forth endlessly between trying to get Python to be fast and trying to get the training part to work in another language.
Yeah, the idea is to take inspiration from Go and similar languages, using the new async (coroutine) features in Python that give it better concurrency handling, and the benefits of types. Without having to deal with a lower-level language.
It's not a value judgment, which I feel (though I can't prove) you are still reading it is. But it isn't. It just is what it is. The performance characteristics of various technologies just... are. It's a mistake to read too much value judgment into it. I don't "hate" PyPy because it's not as fast as C, or love C because it's fast. They've got all sorts of characteristics, and a professional engineer ought to understand them as dispassionately as possible to make decisions about how to solve problems.
PyPy is a solution to "my Python code is running slowly". For very little effort you can obtain a very cheap speedup. It may not be all you need, but it's very engineer-effort cheap. But it certainly isn't a solution to "my Python code is running slowly but I need it to run at C speeds", and there are a ton of other solutions to the problem "My Python code is running slowly", since Python is such a slow language on its own terms. (By contrast, "my C code is running slowly and I've already profiled it a lot, etc." is a huge problem.)
To use Python type hints, and get automatic data validation, serialization, and documentation for your API (including interactive UI docs for your API). All that, even for deeply nested JSON bodies. And by using type hints, you get autocomplete everywhere, type error checks, etc.
Your API gets documented with standards: OpenAPI and JSON Schema.
Or to be able to have WebSockets.
Or for its dependency injection system, that saves you a lot of code and plugins.
Note that if you are currently using Falcon, another route to get many of these features is to use hug (https://github.com/timothycrosley/hug) which inspired many of API Star features back in the day - and is part of the Falcon ecosystem. But there's also a lot of really amazing work done in this ecosystem that hug doesn't currently support - I may have a busy couple of months ahead :).
Yep, and Hug was one of the first tools I saw with this style of declaring parameters with types in the functions, along with APIStar.
Great job! And thanks. It helped inspiring the creation of FastAPI. Apart from other of your tools that I use all the time, like isort.
An advantage I see of Hug: the same Hug application can be a CLI app.
A couple advantages I would see of FastAPI (disclaimer, I'm the creator :) ):
* The API schema uses the standards OpenAPI and JSON Schema
* It includes a couple of interactive API documentation web user interfaces (Swagger UI, and ReDoc). Thanks to being OpenAPI.
* It uses standard Python type hints, not custom types included as part of the library.
* The dependency injection system.
* Websockets.
Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted hug to be - it's really inspiring to see someone build that.
Just wanted to second @tiangolo's "Thanks for paving the way with Hug" - Absolutely yup! It's a lovely bit of interface design - definitely had a really positive impact on the space.
i don't understand why people do this - build these frameworks. it's hundreds of independent labor hours and forgoes the key value prop of python (or whatever language they're reimplementing the wheel in): the existing ecosystem. i would never use this over flask or django because the community around each of those frameworks. that includes plugins, docs, blog posts, SO posts, etc. further more i'm not going to trust that one shop will exist forever and maintain this framework to the same extent that django is maintained. so in effect by adopting this framework i take on the maintenance responsibility. but why would i ever do that? it's not interesting work (very little groundbreaking research left in the http server space i think), it's thankless, and it's just completely unnecessary - every time i submit a PR i'll be looking enviously at django foundation's latest release.
so why would anyone write something like this and why would anyone ever adopt? if you're going for speed without ecosystem then just use Go or Java or C# to begin with. is it just NIH syndrome?
I created the mosts popular Docker images for Flask. I've been building APIs with Flask for a long time, with several teams, using many of its plug-ins, etc. All that learning was inherited by FastAPI. To reduce development time and effort.
About Django:
If you are building APIs with Django, chances are you are using Django-REST-Framework. It was built by Tom Christie. He then built APIStar, improving over what Django-REST-Framework could do. Then he had to stop building APIStar to dedicate himself to Starlette, the new super-fast microframework. FastAPI is heavily inspired by APIStar, and based on Starlette. And uses Python type hints even more.
About plug-ins:
If you refer to plugins to do: authentication, data validation, data serialization, documentation, automatic API docs, compatibility with all SQL and NoSQL, dependency injection, Websockets, Testing, GraphQL... it's all included. Even though it's a mini-framework. Most of the functionality that is normally achieved with plugins is included.
Also, it's heavily integrated into the ASGI ecosystem, so, you have plug-ins to handle Django-Channels like Websockets, serverless deployments, Socket-IO, etc.
Give it from 5 to 20 minutes. That's enough to decide if you like it or hate it.
There's a pretty good reason there's a lot of folks building new frameworks for Python in this space right now: async.
Unlike WSGI frameworks we're now able to support WebSockets, lightweight backgrounds tasks, super-high-throughput performance, and all sorts of other goodies, that Flask, Django et al. aren't necessarily able to excel in.
Good news is that it's pretty likely that some of this may eventually feedback into Django, Flask, and others, but in the meantime it's a case of trying to bring the Python async ecosystem up to feature-parity with existing thread-concurrency frameworks as quickly as we possibly can.
Simply because any sufficiently old Django app has the same intro curve as any other (possibly customised) framework.
Have you actually used Flask, by the way? Or the older version of it called Pyramid? The truth with it is that it's not only complex, but also doesn't prefer any of it's optional components. Any project you'll be building in it is going to be custom anyway.
> Have you actually used Flask, by the way? Or the older version of it called Pyramid?
Flask is in no way related to Pyramid. It came out of an April Fools joke in 2010 (http://lucumr.pocoo.org/2010/4/3/april-1st-post-mortem/). Pyramid, OTOH comes out of the Plone/Zope communities (it used to be known as repoze.bfg).
I wrote a web (WSGI) framework in python because I didn't care for the abstractions of some of the larger ones.
It was a good bit of fun, and it was faster than anything else at the time. Much of the speed came from doing less out of the box. Additionally, it didn't attempt to handle any of the actual connection layer. Everything is done via the WSGI interface, which I think is a great abstraction.
It is based on standard Python type hints. Using them, you get automatic data validation, serialization, and documentation. Including deeply nested JSON documents. And you get editor completion and checks everywhere.
Designed around the OpenAPI (Swagger) and JSON Schema standards.
It includes 2 alternative interactive API documentation systems that are generated automatically.
OAuth2 capable from the start (including JWT). Dependency Injection system, compatible with all databases (relational and NoSQL), Websockets, GraphQL, CORS, etc.
- Just Modern Python
- Editor support
- Short
- Unlimited "plug-ins"
Would it be fair to say that this is Starlette + an API schema + OAuth2 + data validation?
[1] https://fastapi.tiangolo.com/features/#fastapi-features
In FastAPI you declare the parameters of your request (including deeply nested JSON bodies) as function parameters.
So, "editor support" here means, for example, autocomplete even for deeply nested models.
Also, you get automatic data validation and serialization. Automatic detailed errors in your API responses.
Also, it has a powerful dependency injection system, that helps in a lot of cases.
In two flavors:
* With PostgreSQL and SQLAlchemy: https://github.com/tiangolo/full-stack-fastapi-postgresql
* With Couchbase: https://github.com/tiangolo/full-stack-fastapi-couchbase
Not only that, but Go has best in class editing support in VSCode and Vim, has an official code formatting tool (sorry black), and makes writing concurrent code painless with a syncronous abstraction (sorry asyncio).
Also it may have good response times in a vacuum but there’s still the Python memory tax, startup times (which matter when you need to scale horizontally), and scaling of latency to think about.
We're building out an async ecosystem here that makes it way more performance-competitive with Node and Go.
For a lot of folks it's going to hit a sweet spot of developer productivity plus ability to scale up hugely. That's a big deal.
Doesn't mean you have to use it, but there's no need to neg on the great work folks are doing in this space just because Python's not your preferred language of choice.
And maybe the dependency injection system.
And Python's ecosystem with lots of packages.
And that Python is the best/main way to do Machine Learning/Deep Learning.
I personally don't think new asyncio (Python 3.6) is more difficult, but that's more personal taste.
Indeed, FastAPI inherited benefits from ideas in Go and other languages and frameworks.
Golang has libraries for all of the things you mentioned, and web tools to generate APIs based on those schemas. There's no advantage here over Go.
> And maybe the dependency injection system.
Go has interfaces, which facilitates easy DI. No advantage there, and Go sells itself on not having a magic DI framework like the crap Angular 1 had.
> And Python's ecosystem with lots of packages.
Python's ecosystem may have more packages taken as a whole, but Go has a richer web and infrastructure community thanks to being a web first language and growing out of the DevOps community.
> And that Python is the best/main way to do Machine Learning/Deep Learning.
Which means nothing. You shouldn't be running ML in your web server. You use grpc or http to make requests to your ML backend, or generate a config for the web server to consume.
> I personally don't think new asyncio (Python 3.6) is more difficult, but that's more personal taste.
Even if it isn't more difficult, functions have to be colored async which leads to ecosystem fragmentation. It's a huge pita.
Have you considered that maybe not every one wants have anything to do with the 8th wonder of the world that is Go?
Take it easy pal, let people enjoy things.
Would you cite some? I would love to see the links, packages, etc. And how could you achieve the same in Go:
Having a single type declaration, get web data validation, serialization, documentation with OpenAPI and automatic clear error responses.
I would love to see it, because before building FastAPI I looked for it in Go-land a lot too, and didn't find it, not even closer to the tools that already existed in Python.
Tom Christie has been quietly building what's starting to look like an async first decoupled version of django:
- https://github.com/encode/starlette
- https://github.com/encode/orm
- https://github.com/encode/typesystem
- https://github.com/encode/databases
- https://github.com/encode/apistar
- https://github.com/encode/uvicorn
What it adds is automatic data validation, serialization, and documentation, with Python type hints. All using Pydantic.
So, you declare request parameters and bodies with standard Python type hints (even for deeply nested JSON bodies) and it automatically does all that.
It also has a simple but powerful dependency injection system.
And thanks to Tom Christie's work, it is compatible with all those tools too (databases, orm, uvicorn, all from Starlette, etc).
Yes, most of the tests come directly from the docs, that way, by having full test coverage, means that at least a big part of the functionality is not only tested but also documented somewhere.
Small wrinkle: I spotted a broken link on the "deployment" page - "Bigger applications with multiple files" doesn't link to the right place (in fact it links nowhere, the `href` attribute has no value).
That's great!
> Small wrinkle [...]
Oops, good catch! Thanks. It's fixed now.
Molten is based on WSGI, FastAPI is based on ASGI.
So, you can do async/await stuff in FastAPI.
FastAPI inherits directly form Starlette, so it inherits its benefits, like testing tools, GraphQL in-process background tasks, etc.
And it benefits from the ASGI ecosystem, for example with plugins to handle Django-Channels like Websockets, deployment to "serverless", even including other tools like Socket-IO.
FastAPI is based on Pydantic instead of an internal library for declaring schemas, so any improvements there are inherited here.
It supports Flask like route decorators.
The dependency injection is simpler, probably more intuitive (but this is more subjective). The same with several other parts.
But again, Molten is a great tool, and was one of the tools that inspired FastAPI (it's even mentioned in the docs).
You can have semi-automatic data validation, serialization (converting from JSON to Python data types, etc). And an automatic web user interface that documents your API. You don't have to do anything to have that web interface, it's done automatically from your definitions of the data types that you need.
It is also compatible with Jinja templates.
It's like a modern Flask with several benefits, especially for web APIs.
- C library everywhere ( network, serialization ... )
- server that manages process ect ...
At some point if you need that kind of things just pickup a language that does it out of the box.
I view this as a strong benefit in python. Write your app, and if you need to really squeeze performance in some critical area, writing a C/C++ extension is simple enough.
So, if we can use it, take advantage of its benefits and have tools like this that simplify everything without too many constraints, I would say it's a good tradeoff.
This is such a terrible state of affairs. There are so many times I've wanted to generate synthetic training data efficiently and iterate in a tight training loop where I've gone back and forth endlessly between trying to get Python to be fast and trying to get the training part to work in another language.
If it's IO, check asyncio tools. E.g. aiofiles.
In the grand landscape of programming language performance, it tops out at middling on practical code.
If we wanted to have the absolute best performance, we would have to write web apps in C. But it would be quite more cumbersome.
PyPy is a solution to "my Python code is running slowly". For very little effort you can obtain a very cheap speedup. It may not be all you need, but it's very engineer-effort cheap. But it certainly isn't a solution to "my Python code is running slowly but I need it to run at C speeds", and there are a ton of other solutions to the problem "My Python code is running slowly", since Python is such a slow language on its own terms. (By contrast, "my C code is running slowly and I've already profiled it a lot, etc." is a huge problem.)
Your API gets documented with standards: OpenAPI and JSON Schema.
Or to be able to have WebSockets.
Or for its dependency injection system, that saves you a lot of code and plugins.
You can check the features here: https://fastapi.tiangolo.com/features/
And you can see alternatives and comparisons here: https://fastapi.tiangolo.com/alternatives/
(DISCLAIMER: I am the creator of hug)
Great job! And thanks. It helped inspiring the creation of FastAPI. Apart from other of your tools that I use all the time, like isort.
An advantage I see of Hug: the same Hug application can be a CLI app.
A couple advantages I would see of FastAPI (disclaimer, I'm the creator :) ):
* The API schema uses the standards OpenAPI and JSON Schema * It includes a couple of interactive API documentation web user interfaces (Swagger UI, and ReDoc). Thanks to being OpenAPI. * It uses standard Python type hints, not custom types included as part of the library. * The dependency injection system. * Websockets.
Honestly, what you've built looks super solid and polished. In many ways, it's what I wanted hug to be - it's really inspiring to see someone build that.
Thanks for paving the way with Hug. And thanks for helping make the Python ecosystem a friendly, and welcoming community.
i don't understand why people do this - build these frameworks. it's hundreds of independent labor hours and forgoes the key value prop of python (or whatever language they're reimplementing the wheel in): the existing ecosystem. i would never use this over flask or django because the community around each of those frameworks. that includes plugins, docs, blog posts, SO posts, etc. further more i'm not going to trust that one shop will exist forever and maintain this framework to the same extent that django is maintained. so in effect by adopting this framework i take on the maintenance responsibility. but why would i ever do that? it's not interesting work (very little groundbreaking research left in the http server space i think), it's thankless, and it's just completely unnecessary - every time i submit a PR i'll be looking enviously at django foundation's latest release.
so why would anyone write something like this and why would anyone ever adopt? if you're going for speed without ecosystem then just use Go or Java or C# to begin with. is it just NIH syndrome?
Good question. I ask the same questions myself every time. And I avoided creating FastAPI for a long time.
I tried a whole lot of tools. And FastAPI got inspiration from a lot of them.
A more detailed explanation is here: https://fastapi.tiangolo.com/alternatives/
More details about Flask and Django:
About Flask:
I created the mosts popular Docker images for Flask. I've been building APIs with Flask for a long time, with several teams, using many of its plug-ins, etc. All that learning was inherited by FastAPI. To reduce development time and effort.
About Django:
If you are building APIs with Django, chances are you are using Django-REST-Framework. It was built by Tom Christie. He then built APIStar, improving over what Django-REST-Framework could do. Then he had to stop building APIStar to dedicate himself to Starlette, the new super-fast microframework. FastAPI is heavily inspired by APIStar, and based on Starlette. And uses Python type hints even more.
About plug-ins:
If you refer to plugins to do: authentication, data validation, data serialization, documentation, automatic API docs, compatibility with all SQL and NoSQL, dependency injection, Websockets, Testing, GraphQL... it's all included. Even though it's a mini-framework. Most of the functionality that is normally achieved with plugins is included.
Also, it's heavily integrated into the ASGI ecosystem, so, you have plug-ins to handle Django-Channels like Websockets, serverless deployments, Socket-IO, etc.
Give it from 5 to 20 minutes. That's enough to decide if you like it or hate it.
Unlike WSGI frameworks we're now able to support WebSockets, lightweight backgrounds tasks, super-high-throughput performance, and all sorts of other goodies, that Flask, Django et al. aren't necessarily able to excel in.
Good news is that it's pretty likely that some of this may eventually feedback into Django, Flask, and others, but in the meantime it's a case of trying to bring the Python async ecosystem up to feature-parity with existing thread-concurrency frameworks as quickly as we possibly can.
Have you actually used Flask, by the way? Or the older version of it called Pyramid? The truth with it is that it's not only complex, but also doesn't prefer any of it's optional components. Any project you'll be building in it is going to be custom anyway.
Flask is in no way related to Pyramid. It came out of an April Fools joke in 2010 (http://lucumr.pocoo.org/2010/4/3/april-1st-post-mortem/). Pyramid, OTOH comes out of the Plone/Zope communities (it used to be known as repoze.bfg).
FastAPI learned a lot from many of these tools and techniques.
It was a good bit of fun, and it was faster than anything else at the time. Much of the speed came from doing less out of the box. Additionally, it didn't attempt to handle any of the actual connection layer. Everything is done via the WSGI interface, which I think is a great abstraction.
Encode, the team that develops Starlette, also develops Django REST Framework. They help make the Python web development ecosystem what it is.
Even the heaviest inspiration is form APIStar (now "deprecated" as a server). Built by him too.