Building Web App with Django and FastAPI
Last Updated :
28 Jun, 2024
Django is a powerful and popular web framework for building robust web applications with Python. It comes with a lot of built-in features, including an ORM, an authentication system, and a powerful admin interface. However, there are scenarios where you might want to integrate Django with FastAPI, a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
FastAPI is designed for creating fast and efficient APIs and provides features like automatic generation of OpenAPI and JSON Schema, dependency injection, and asynchronous request handling. Integrating FastAPI with Django can leverage the strengths of both frameworks, enabling rapid development of high-performance web applications.
In this article, we will explore what FastAPI is, its benefits, and how to integrate it into a Django project with practical examples.
What is FastAPI?
FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python-type hints. Some of its key features include:
- High performance: FastAPI is one of the fastest web frameworks available, thanks to Starlette for the web parts and Pydantic for the data parts.
- Ease of use: FastAPI is designed to be easy to use and learn. The syntax is clean and intuitive.
- Automatic documentation: It automatically generates OpenAPI and JSON Schema documentation, making it easy to develop and maintain APIs.
- Asynchronous support: FastAPI supports asynchronous programming, which can lead to better performance for IO-bound operations.
- Dependency injection: FastAPI provides a simple and powerful way to manage dependencies in your application.
Creating a Django Project with FastAPI Integration
Let's create a Django project and integrate FastAPI into it. We'll walk through the setup and show you the code for each file.
Step 1: Setting Up Your Django Project
First, create a new Django project. If you haven't already installed Django, you can do so using pip:
pip install django
Create a new Django project:
django-admin startproject myproject
cd myproject
File Structure
Step 2: Setting Up FastAPI
Next, we need to install FastAPI and Uvicorn (an ASGI server) in our Django project:
pip install fastapi uvicorn
Step 3: Creating a FastAPI App
Create a new Python file for your FastAPI app.For this example, let's create a file named fastapi_app.py inside your Django project directory.
# myproject/fastapi_app.py
Python
# myproject/fastapi_app.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.post("/items/")
def create_item(item: Item):
return item
Step 4: Integrating FastAPI with Django
To integrate FastAPI with Django, we need to create an ASGI application that can serve both Django and FastAPI. We will use Django's get_asgi_application and FastAPI's app together.
Create an asgi.py file in your Django project directory if it doesn't already exist:
Python
# myproject/asgi.py
import os
from django.core.asgi import get_asgi_application
from fastapi.middleware.wsgi import WSGIMiddleware
from fastapi_app import app as fastapi_app
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django_app = get_asgi_application()
app = WSGIMiddleware(django_app)
app.mount("/api", fastapi_app)
Step 5: Running the Application
To run the application, use Uvicorn:
uvicorn myproject.asgi:app --reload
Now, your application will be available at http://127.0.0.1:8000. The Django app will be accessible as usual, and the FastAPI app will be available under the /api path.
Access the FastAPI root endpoint at http://127.0.0.1:8000/api/
Handling Authentication and Permissions
Using Django Authentication
To use Django’s authentication system with FastAPI, you can leverage Django’s built-in user authentication:
- Create Django Users: Use Django’s admin interface or manage.py commands to create users.
- Middleware for Authentication: Use middleware to handle authentication tokens or session management.
Example of integrating Django authentication with FastAPI:
Python
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from django.contrib.auth.models import User
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def get_current_user(token: str = Depends(oauth2_scheme)):
try:
user = User.objects.get(auth_token=token)
return user
except User.DoesNotExist:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
@app.get("/users/me", response_model=User)
def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
Advantages of Using FastAPI with Django
- Scalability: FastAPI's asynchronous capabilities can handle more simultaneous connections, improving scalability.
- Documentation: FastAPI automatically generates OpenAPI and JSON Schema documentation, which is useful for API development and testing.
- Speed: FastAPI is designed for performance, using async and await capabilities of Python 3.6+.
Conclusion
Using FastAPI with Django combines the strengths of both frameworks, allowing you to build high-performance APIs with FastAPI while leveraging Django’s robust features for web application development. This integration can help you create scalable, efficient, and well-documented applications.
Experiment with the setup to suit your project's needs and take advantage of the best features both frameworks have to offer.
Similar Reads
Building APIs using FastAPI with Django
Combining FastAPI and Django can leverage the strengths of both frameworks: FastAPI's high performance for building APIs and Django's powerful ORM and admin interface. In this guide, we'll outline how to integrate FastAPI into a Django project to build high-performance APIs. In this article, we will
3 min read
Building an Issue Tracker with Django
In this article, we will guide you through creating an Issue Tracker using Django. A Django issue tracker is a web-based application designed to help software development teams manage and track bugs, tasks, and feature requests efficiently. Leveraging Django's powerful framework, this project provid
6 min read
Build a URL Size Reduce App with Django
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In this article, we will learn to build a URL shortener using Django. A URL shortener is used to reduce the size of long URLs. Short URLs are better for sharing purposes. In this article, we wi
5 min read
Comparison of FastAPI with Django and Flask
For starters, as you may know, Python is an interpreted programming language that is becoming more and more popular for building web applications. However, there are numerous web frameworks to choose from but they all have different use cases. In this article, we will look at 3 frameworks which are
4 min read
Django - Dealing with warnings
Prerequisite : Django - Creating project Django is a great framework which provides you a lot of pre-defined services and workflow so that one can work flawlessly. Django apps are designed to make your code clean and reusable. Django works on the concept of DRY which means Don't Repeat Yourself. Aft
2 min read
Django REST API - CRUD with DRF
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around the Django Framework. There are three stages before creating an API through the REST framework, Converting a Modelâs data to JSON/XML format (Serialization), Rendering this data to the view, and Cr
7 min read
Fetching and Displaying Data with HTMX and FastAPI
HTMX allows us to utilize current AJAX methods in HTML directly, while FastAPI is a strong backend framework for quick and efficient API development. This artilce will examine the way of combining HTMX with FastAPI to develop dynamic web applications. Setting Up FastAPIStep1. First we need Python in
3 min read
Build a Flashcards using Django
Flashcards are an effective tool for studying and memorizing information. Building a flashcards application using Django allows you to create a robust, scalable, and easy-to-maintain web application. This article will guide you through the process of creating a flashcard app using Django. In this ar
5 min read
Django - Creating apps | Set - 2
In the previous article, we discussed why apps are important in Django project management? What are the benefits of using Django apps? In this article, we will discuss what are we going to build and how do apps play a vital role in Django projects? Project outline - We will build a localhost e-comme
2 min read
Django - Creating Apps | Set - 1
Prerequisites: Django â Dealing with warnings Why do we need apps? In Django Set 2 (Creating a Project), we saw how we can display text in our browser using Django but that is not the best and pythonic way. Django recommends using the project-app relationship to build Django projects. Any website co
1 min read