Open In App

Building Web App with Django and FastAPI

Last Updated : 28 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

llll

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/

oop

Handling Authentication and Permissions

Using Django Authentication

To use Django’s authentication system with FastAPI, you can leverage Django’s built-in user authentication:

  1. Create Django Users: Use Django’s admin interface or manage.py commands to create users.
  2. 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

  1. Scalability: FastAPI's asynchronous capabilities can handle more simultaneous connections, improving scalability.
  2. Documentation: FastAPI automatically generates OpenAPI and JSON Schema documentation, which is useful for API development and testing.
  3. 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.


Next Article
Article Tags :
Practice Tags :

Similar Reads