DEV Community

rajshirolkar
rajshirolkar

Posted on • Updated on

FastAPI - moving on from Flask

If you're a Python developer, you've probably heard of Flask, the micro web framework that has gained a lot of popularity in recent years. However, if you're looking to build a high-performance web application, you may want to consider FastAPI as an alternative.

One of the major drawbacks of Flask is that it is not built for concurrency. In Python, implementing multithreading can be very complicated, as the language itself has some limitations. This means that if you want to build a web application that can handle a high volume of requests, Flask may not be the best choice.

Async support

One of the major limitations of Flask is its lack of async support. In Python, multithreading is very complicated, and the global interpreter lock (GIL) makes it difficult to achieve true parallelism. This is where async programming comes in. Async allows you to write code that can perform IO-bound and high-level structured network code in an async manner.

FastAPI, on the other hand, fully supports async. It's built on top of Starlette, which is an async-compatible web framework, and uses the new async/await syntax introduced in Python 3.5. This means you can write async code in FastAPI just like you would in any other async framework, such as aiohttp or Sanic.

Here's an example of a simple async endpoint in FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}
Enter fullscreen mode Exit fullscreen mode

Compare this to the equivalent in Flask:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

Performance

FastAPI is also faster than Flask. It uses the uvicorn server, which is built on top of the asyncio library and the uvloop() event loop. uvloop() is a fast implementation of the asyncio event loop, written in Cython and based on libuv, the same library that powers Node.js. This means that FastAPI can handle a lot more requests per second compared to Flask.

Image description

In fact, a benchmark by the FastAPI team showed that FastAPI is up to 3x faster than Flask in some cases. Here's a comparison of the two frameworks using the wrk tool:

For Flask -

Flask (Python 3.7, uWSGI 2.0.18.1):
Running 30s test @ http://127.0.0.1:5000/
  12 threads and 400 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    28.41ms   20.74ms 635.86ms   80.54%
    Req/Sec     2.00k   439.36     3.44k    80.91%
  240973 requests in 30.09s, 41.97MB read
  Socket errors: connect 0, read 240973, write 0, timeout 0
  Non-2xx or 3xx responses: 240973
Requests/sec:   7975.34
Enter fullscreen mode Exit fullscreen mode

For FastAPI -

FastAPI (Python 3.7, uvicorn 0.11.2):
Running 30s test @ http://127.0.0.1:8000/
  12 threads and 400 connections
  Thread Stats Avg Stdev Max +/- Stdev
    Latency 5.12ms 3.29ms 37.45ms 85.08%
    Req/Sec 6.70k 1.37k 10.22k 65.39%
  802934 requests in 30.10s, 134.69MB read
  Socket errors: connect 0, read 802934, write 0, timeout 0
  Non-2xx or 3xx responses: 802934
Requests/sec: 26702.16
Enter fullscreen mode Exit fullscreen mode

As you can see, FastAPI is able to handle almost 3x the number of requests per second compared to Flask. This makes it a great choice for building high-performance APIs.

Flask

Image description

FastAPI

Image description

Data validation and parsing

FastAPI also has built-in support for data validation and parsing using Pydantic. Pydantic is a library that allows you to define your API's request and response bodies using Python's built-in type hints. FastAPI will then automatically validate the request data and parse it into the correct types.

Here's an example of a request body defined using Pydantic in FastAPI:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
Enter fullscreen mode Exit fullscreen mode

FastAPI will automatically validate the request data and return any validation errors if the data is invalid. This saves you a lot of time and effort compared to manually validating the request data in Flask.

Conclusion

In conclusion, if you're a Python developer looking to build APIs, you should consider using FastAPI instead of Flask. It's a modern, fast, and easy-to-use web framework that fully supports async programming and comes with built-in support for data validation and parsing. Give it a try and see how it can improve your API development workflow.

Top comments (0)