5 Advance Features of FastAPI You Should Try (2024)

Mounting applications, API routers, Jinja templates & much more

5 Advance Features of FastAPI You Should Try (1)

Published in

Level Up Coding

·

10 min read

·

Jan 17, 2022

--

FastAPI is a modern web framework developed in Python. It has gained a lot of attraction in recent times. Its development structure is very much similar to Flask, which was the de-facto option for anyone starting with web development using Python. FastAPI is easy to use, its documentation is well written and easy to follow along.

FastAPI offers all the standard features of an API building tool but it is not limited to this. It comes with a lot of flexibility such as backward WSGI mounting support which, most of the users, are not aware of.

In this article, I will introduce some of the advanced features of FastAPI which I have been using for my recent projects. Also, the following use cases assume that you have a basic knowledge of FastAPI.

1. Include Flask, Django, Dash, or any other WSGI

FastAPI is an ASGI web framework. What this means is that different requests don’t have to wait for the others before them to finish doing their tasks. Different requests can do their task completion in no particular order. On the other hand, the WSGI frameworks process request in a sequential manner.

FastAPI allows any type of WSGI application like Flask to be mounted inside a FastAPI application. What this means is that on the root level, you can have the main FastAPI app and further, for different routes, you can have WSGI applications such as Flask which will handle all requests for that specific path.

One of the use cases of this, which I have been using for my project is mounting plotly-dash as WSGI middleware. I had mounted the dash server for the dashboard route of my website which segregates the dashboard logic from the main FastAPI application. This also provides the flexibility to disable the dashboard anytime the server load is more. Here is an abstract implementation of WSGI middleware mounting which I did for one of the projects.

Below are the example contents for the dashboard.py file:

To include this dash server as an independent application within FastAPI, simply wrap the WSGI application object in the WSGIMiddleware class and pass this wrapped object as a parameter in the mount function of the root FastAPI object. The mount function also takes in the path on which this application should be used. For instance, this dashboard would be mounted on the “/dashboard” path. See the contents of the main.py file below:

If anyone visits the dashboard route, all those requests would be temporarily redirected to the dash server.

5 Advance Features of FastAPI You Should Try (3)

Link to my project which is backed by FastAPI and uses all the concepts explained in this article: https://ipuresultskg.herokuapp.com/ . It’s a result portal which I developed for my University. Use my enrollment number to experience the website: 43114803118 (batch 2018)

2. Mount different FastAPI apps for different routes

Following the same rules of mounting different WSGI applications for different routes, you can also mount different FastAPI applications within the FastAPI application. This would mean that every sub-FastAPI application would have its docs, would run independent of other applications, and will handle its path-specific requests. To mount this, simply create a master application and sub-application file. Now, import the app object from the sub-application file to the master application file and pass this object directly to the mount function of the master application object. This workaround doesn’t require any middleware. See an example below:

Below are the contents for the apiv1.py file (sub-application 1):

And here is the code for the apiv2.py file (sub-application 2):

Now, we can mount both of these sub-applications in the master application. See the code for the master.py file:

If you make requests to respective paths endpoints, the request will be handled by those sub-applications.

5 Advance Features of FastAPI You Should Try (4)

3. Separate your FastAPI Routes into different files

It usually happens that as your application grows bigger, it becomes a mess to manage all the routes in one place. Sometimes, overlaps can happen or you might be duplicating a route unaware of the consequences later. What if there was a system where you could group your routes into different file structures and easily manage them?

FastAPI has a system of APIRouters. These can be considered to be mini FastAPI apps that are part of the bigger application. This means that one can break bigger application routes into small units of APIRouters and mount individual APIRouters in the main application.

Do note here that these APIRouters are part of the bigger application and not the independent applications like the ones we saw in the above two sections. Therefore, all the routes from all the APIRouters will be listed in the main application documentation.

These APIRouters can have separate prefixes to the path operations, tags, dependencies, & responses. Therefore to implement this, you need to import the APIRouter class from fast API and then use its object to create routes as you would do in a usual FastAPI application.

Let’s see an example. Suppose we are building a library management system and we want to handle books and novel data separately. Let this be the code for the book.py file:

And this is the code for the novel.py file:

Now, to include both the routers in the main application, simply import the object of APIRouter and pass these in the include_router function of the main FastAPI application object. We will also add the prefixes for these routers so that the same endpoints in both routers don’t conflict. See the implementation below:

If you hit the “/book/info” and the “/novel/info” endpoints, you will get different responses depending upon how you handled those inputs in the APIRouters.

In this way, you can have multiple APIRouters to handle parameters based on what type of operation you want to perform for those groups of endpoints.

4. Add static files and Jinja templates

FastAPI is not limited to serving as a framework for creating APIs. You can serve static files such as HTML, CSS, JS and incorporate Jinja templating engine, as you would do in Flask. This means that you can host a complete website with FastAPI.

Let me correlate this to Flask. In the Flask framework, you need to have a folder with the name “templates”, where you can have all the HTML files with Jinja templating (let me know in the comments if you would like me to create a detailed article on Jinja templating engine) and in the main application, one can directly use the render_template function from flask to return these templates with the data to be filled in these templates.

In FastAPI, on the abstract level, the process remains the same but with few changes. Step by step process:-

  1. First, you need to create an object for Jinja templates where you need to specify the path of the templates folder. In FastAPI, there is no constraint on the folder name, you can name it anything. You only need to provide the folder path here. Technically, you need to import the Jinja2Templates class from the fast API templating module and create an object for that class with the folder path.
  2. Next, you need to provide the response_class in the FastAPI route method (ex: GET, POST) as HTMLResponse class. This class can be imported from the fast API responses module. Also, you need to create a request parameter of the “Request” class type in the decorator function. This class can be imported from the fast API module.
  3. To render and provide data to these templates on hitting the respective endpoints, you need to return the Jinja2Templates class object “TemplateResponse” function. This function takes in the HTML template name and the context dictionary. The context dictionary must have the “request” key with value as the request parameter you created in the decorator function. The data to be sent to the Jinja templates can be added in this context dictionary as key-value pair.

Here is the code implementation of the above steps:

Now, in the HTML templates, you can fill in the variables, as per the syntax of the Jinja engine, with the name used as the keys in the context dictionary.

Start the FastAPI application and you will have this output:

5 Advance Features of FastAPI You Should Try (5)

To include all the images, JS, and CSS files in HTML, in Flask, you would use the url_for and provide the folder name as “static” followed by the filename parameter. In FastAPI, the process is easier. Simply,

  1. Create an object for StaticFiles class from the fast API static files module and provide the folder path to the static file. Again, no constraint on the folder name.
  2. Mount this static files object to one of the paths, preferably “static” to avoid confusion and provide this mount a name to be used internally by FastAPI.

I have added the logic for the static files in the same code used for Jinja files serving:

Now, suppose you have an image “img1.png”, which you want to include in your HTML file. Simply, in the src attribute of the img tag, use the path as:

/<path_on_which_static_files_are_mounted>/<image_directory>/<image_name>

(Here image directory depends on your file structure)

Here is the updated code for the above used Jinja template HTML file with the image tag :

And we will have the output for this as:

5 Advance Features of FastAPI You Should Try (6)

In this way, you can add up all the files and create a full-fledged website backed by FastAPI.

5. Simulate Configuration Handling of Flask in FastAPI App

If you are someone who has been using the Flask web framework for quite some time, you must be aware of app configurations. You can define some of the parameters for your application to be accessed by any part of the application. These usually comprise environment variables. The config attribute, a subclass of the dictionary data structure, resides in the Flask class object. It is where all the configurations are stored. This is especially useful when you are want to hardcode some parts of the application and make calls for these anywhere in the application.

This is what you would do in Flask to define such configuration parameters:

FastAPI doesn’t have this support. Though some of you might think that the application state can be used in this case, but as per Tiangolo (the creator of FastAPI) suggestion, the APIRouter won’t have access to this state. Due to this, even if you save some configuration in the application state, this won’t be shared among all the parts of the application and ultimately won't serve any purpose.

Therefore, a simple workaround for this, suggested by Tiangolo, is to use the Pydantic BaseSettings class and create a model for these settings. This class offers validation features and type annotations. These features set them apart from the usual environment variables where they can only handle string-type values.

To put this together in your FastAPI application, simply import the BaseSettings class from Pydantic and create the subclass for your settings/configurations. These are Pydantic classes and therefore, you can add default values, Field(), and much more. Let me present you with an example to implement this.

Below are the contents for the config.py file:

Here, I have defined openapi_url as an empty string. It will disable the docs generation for the FastAPI application. In the main application file, create an object for the configuration model and access the parameters as you would do in a dictionary type data structure:

This is how you can use this model as a global configuration across your application. It also eliminates the dependency of FastAPI to configure other parts of the application.

These were all the advanced use cases of FastAPI which I came across while developing my projects. Although documentation is the best way to learn more about these concepts, I have tried to provide a wider and practical scenario where you can apply these concepts. FastAPI advance use cases are not limited to the ones discussed in this article. It is an amazing framework that is slowly capturing the whole tech industry.

If you want to read/explore every article of mine, then head over to my master article list which gets updated every time I publish a new article on any platform!

For any doubts, queries, or potential opportunities, you can reach out to me via:

Previous Article:

5 Advance Features of FastAPI You Should Try (2024)

FAQs

What are the advantages of FastAPI? ›

FastAPI simplifies concurrency by eliminating the need for an event loop or async/await management. The initial path function can then be specified as coroutines using async def and await specific locations by developers. FastAPI supports a dependency injection solution that is simple and easy to use.

What are the best practices for structuring a FastAPI project? ›

  • Project Structure. Consistent & Predictable. ...
  • Excessively use Pydantic for data validation. ...
  • Use dependencies for data validation vs DB. ...
  • Decouple & Reuse dependencies. ...
  • Don't make your routes async, if you have only blocking I/O operations. ...
  • Migrations. ...
  • BackgroundTasks > asyncio. ...
  • Save files in chunks.
Aug 29, 2022

What is the main function of FastAPI? ›

FastAPI is a Python framework and set of tools that enables developers to use a REST interface to call commonly used functions to implement applications. It is accessed through a REST API to call common building blocks for an app. In this example, the author uses FastAPI to create accounts, login, and authenticate.

What makes FastAPI fast? ›

Unlike Flask, FastAPI doesn't have a built-in development server, so an ASGI server similar to Daphne or Uvicorn is used when required. FastAPI's speed is largely because ASGI is the server in which it was built and it supports asynchronous code.

What are the advantages of FastAPI over Django? ›

Performance: FastAPI is generally faster than Django due to its use of modern Python features such as async/await, type annotations, and the Pydantic library for data validation. This makes it well-suited for building APIs that require high throughput or low latency.

What is the point of Python FastAPI? ›

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. The key features are: Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.

How is FastAPI better than Flask? ›

FastAPI is way faster than Flask, and it's actually one the fastest web frameworks for Python. The only framework that is faster than FastAPI is Starlette (fun fact - FastAPI is actually built on Starlette). It used to be hard, but since Python 3.4 Async I/O was added. FastAPI allows out-of-the-box concurrency.

What is middleware in FastAPI? ›

A "middleware" is a function that works with every request before it is processed by any specific path operation. And also with every response before returning it. It takes each request that comes to your application. It can then do something to that request or run any needed code.

What is the difference between FastAPI and REST API? ›

FastAPI is way faster than Django Rest Framework and is one of the fastest web frameworks for Python. The only more rapid frameworks are Starlette and Uvicorn (fun fact - FastAPI is built on top of Starlette). It used to be challenging, but since Python 3.4 Async I/O was added.

How many request can FastAPI handle? ›

FastAPI (Async) - Python

FastAPI in asynchronous mode clocks in at ~228 requests per second.

How do I optimize my API speed? ›

Caching is one of the best ways to improve API performance. If you have requests that frequently produce the same response, a cached version of the response avoids excessive database queries. The easiest way to cache responses is to periodically expire it, or force it to expire when certain data updates happen.

Can FastAPI replace Django? ›

In conclusion, Django is perfect if you want to build robust full-stack web applications because it has several functionalities and works very well in production. On the other hand, FastAPI is perfect if you're looking for high-performance or scalable applications.

Why is FastAPI faster than Flask? ›

Inbuilt data validation

It can detect invalid datatypes during the run and returns the reason for bad input in JSON format. FastAPI makes use of the Pydantic library for this purpose, which greatly simplifies the validation process and ensures faster typing than it would have been by hand.

Which big companies use FastAPI? ›

Large companies like Uber and Netflix use it to develop some of their applications.

Is FastAPI enough for backend? ›

Performance – FastAPI is a very fast backend framework in terms of performance. Built upon the ASGI (Asynchronous Server Gateway Interface) instead of WSGI (Web Server Gateway Interface), it is actually one of the fastest Python web frameworks, since it also supports asynchronous code and concurrency.

Is FastAPI good for big projects? ›

Flask: Performance. FastAPI performs significantly better in terms of efficiency. This happens as a result of asynchronous request processing. This makes FastAPI superior to Flask for larger-scale machine learning projects, especially enterprise ones, as it can handle requests much more efficiently.

Does FastAPI use multiprocessing? ›

With FastAPI you can take the advantage of concurrency that is very common for web development (the same main attraction of NodeJS). But you can also exploit the benefits of parallelism and multiprocessing (having multiple processes running in parallel) for CPU bound workloads like those in Machine Learning systems.

What are the 5 principles for a RESTful API? ›

Principles of Rest API
  • Client-Server decoupling. In a REST API design, client and server programs must be independent. ...
  • Uniform Interface. All API queries for the same resource should look the same regardless of where they come from. ...
  • Statelessness. ...
  • Layered System architecture. ...
  • Cacheable. ...
  • Code on Demand.
Jan 18, 2023

What are the 4 principles of RESTful API? ›

The REST API architecture defines REST principles by four interface controls, including identifying resources, managing resources through representations, enabling self-descriptive communications, and making hypermedia the engine of the application state.

What are the 6 constraints of REST API? ›

The six architectural constraints of REST APIs
  • Client-server architecture. An API's job is to connect two pieces of software without limiting their own functionalities. ...
  • Statelessness. ...
  • Uniform Interface. ...
  • Layered system. ...
  • Cacheability. ...
  • Code on Demand.

How do you design a API to process result faster for that API? ›

5 Ideas for Building Faster APIs
  1. 1) Design Practical Endpoints. ...
  2. 2) Support Partial Resources. ...
  3. 3) Compress Data Responses. ...
  4. 4) Negotiate for Effective Formats. ...
  5. 5) Stream Where Applicable. ...
  6. Final Thoughts.
Jan 22, 2019

What does an effective API strategy look like? ›

An effective API strategy includes full lifecycle API management, strong security, an impressive API portal, and insightful analytics. With an effective API strategy, you can drive innovation in the enterprise and gain a competitive advantage.

What is the most popular API architecture? ›

REST, SOAP, and RPC are the most popular API architectures in use today — let's unpack each one in more detail.

What are the 3 principles for a restful API? ›

The only requirement is that they align to the following six REST design principles - also known as architectural constraints:
  • Uniform interface. ...
  • Client-server decoupling. ...
  • Statelessness. ...
  • Cacheability. ...
  • Layered system architecture. ...
  • Code on demand (optional).

What is the most important feature of REST API? ›

It is stateless

One of the main features of an REST API is that its service is stateless, which means that every time we refer to it, it will be necessary to remind it our data, whether it is our user credentials or any other information.

Can I use FastAPI for production? ›

It gives you a really fast way to deploy your ML to production — and with surprisingly excellent performance. Let's see why you should start using it and why it works so well! For starters, FastAPI contains the word “fast” for a reason.

What is async in FastAPI? ›

Asynchronous Code. Asynchronous code just means that the language 💬 has a way to tell the computer / program 🤖 that at some point in the code, it 🤖 will have to wait for something else to finish somewhere else.

What is the difference between dependency and middleware in FastAPI? ›

Dependency: you use it to run code for preparing variables, authentication and so on. Middleware: you need to check some stuff first and reject or forward the request to your logic.

What are the two types of middleware? ›

Types of Middleware
  • Message Oriented Middleware. ...
  • Object Middleware. ...
  • Remote Procedure Call (RPC) Middleware. ...
  • Database Middleware. ...
  • Transaction Middleware. ...
  • Portals. ...
  • Embedded Middleware. ...
  • Content-Centric Middleware.

What is the response time of FastAPI? ›

While FastAPI response time is around 10ms.

What are the benefits of FastAPI? ›

Pros of using FastAPI
  • Great performance. FastAPI surpasses Flask in terms of performance, and it is one of the fastest Python web frameworks. ...
  • Built-in concurrency. For concurrent programming, Python 3.4 introduced Async I/O. ...
  • Dependency injection support. ...
  • Built-in docs. ...
  • Validation built-in.
Mar 21, 2023

Does FastAPI use OpenAPI? ›

A FastAPI application (instance) has an . openapi() method that is expected to return the OpenAPI schema. As part of the application object creation, a path operation for /openapi.

What is OpenAPI in FastAPI? ›

FastAPI generates a schema using OpenAPI specifications. The specification determines how to define API paths, path parameters, etc. The API schema defined by the OpenAPI standard decides how the data is sent using JSON Schema. Visit http://127.0.0.1:8000/openapi.json from your browser.

What is Pydantic in FastAPI? ›

Pydantic is a Python library for data parsing and validation. It uses the type hinting mechanism of the newer versions of Python (version 3.6 onwards) and validates the types during the runtime. Pydantic defines BaseModel class. It acts as the base class for creating user defined models.

How does FastAPI generate documentation? ›

The automatic documentation is generated from the OpenAPI Specification (OAS), an API description format for REST APIs. In perfectly conventional REST API applications, this automatic documentation might suffice to help clients understand how to use it.

Is FastAPI synchronous or asynchronous? ›

FastAPI runs an async event loop that coordinates the async path functions, and a threadpool for synchronous path functions. A developer doesn't need to know the tricky details, which is a great plus. For example, you don't need to run things like asyncio. gather() or asyncio.

Is FastAPI slow? ›

Unsurprisingly, it is extremely slow to return the data using json. dumps() . I am first reading the data from a file using json. loads() and filtering it per the inputted parameters.

Does FastAPI use threading? ›

When FastAPI is used asynchronously, all tasks are executed in a single thread, while the asyncio event loop manages the processing of concurrent requests by allowing context switches between them.

How do I reduce latency in API? ›

Reducing request latency
  1. Sending requests to the closest regional location.
  2. Compressing the response body.
  3. Sending warmup requests.
  4. Sending requests concurrently with HTTP/1. 1 or HTTP/2.

What causes an API to be slow? ›

The larger the database (more data concerning devices, users, etc.), the longer it will take to sort through all the data and return a result. This also correlates to the back-end where calls are processed on a server.

What to do if API response is slow? ›

The time taken by APIs plays a role in the user experience. One of the ways to handle slow API responses is by having the custom component update the user with wait messages. This article has shown a scalable approach by using NoSQL Database on OCI infrastructure as a cache.

Is FastAPI better than REST API? ›

FastAPI is way faster than Django Rest Framework and is one of the fastest web frameworks for Python. The only more rapid frameworks are Starlette and Uvicorn (fun fact - FastAPI is built on top of Starlette).

What is better than FastAPI? ›

Packages: Django has numerous packages that enable the reusability of code. It is a full-stack web development framework, unlike FastAPI, a minimalistic framework used for developing fast web applications.

Why do you need Uvicorn FastAPI? ›

Unlike the Flask framework, FastAPI doesn't contain any built-in development server. Hence we need Uvicorn. It implements ASGI standards and is lightning fast. ASGI stands for Asynchronous Server Gateway Interface.

Is FastAPI good for Microservices? ›

FastAPI is a Web framework for developing RESTful APIs in Python. It is a great choice when you want to build an app based on microservices.

Why is FastAPI better than Flask? ›

FastAPI is way faster than Flask, and it's actually one the fastest web frameworks for Python. The only framework that is faster than FastAPI is Starlette (fun fact - FastAPI is actually built on Starlette). It used to be hard, but since Python 3.4 Async I/O was added. FastAPI allows out-of-the-box concurrency.

What big companies use FastAPI? ›

Large companies like Uber and Netflix use it to develop some of their applications.

Can you build a website using FastAPI? ›

You can use this as a base to populate with site-specific routes and templates/views for your needs. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. You can code along with this article or download the files.

How much traffic can FastAPI handle? ›

FastAPI in synchronous mode clocks in at ~178 requests per second.

Can I use FastAPI for backend? ›

FastAPI is a Python web framework designed for building fast and efficient backend APIs. It handles both synchronous and asynchronous operations and has built-in support for data validation, authentication, and interactive API documentation powered by OpenAPI.

Which is better FastAPI or Starlette in Python? ›

The same way that Starlette uses Uvicorn and cannot be faster than it, FastAPI uses Starlette, so it cannot be faster than it. FastAPI provides more features on top of Starlette. Features that you almost always need when building APIs, like data validation and serialization.

Is FastAPI asynchronous? ›

The most exciting feature of FastAPI is that it supports asynchronous code out of the box using the async/await Python keywords. Testing FastAPI endpoints are really straightforward and can be done using TestClient provided by FastAPI.

References

Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6527

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.