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 combine the strengths of both Django and FastAPI to create a simple web application. Specifically, we will build a web page that displays "Welcome to GeeksforGeeks" in green color using Django as the primary framework and integrating FastAPI to handle specific API endpoints.
Building APIs using FastAPI with Django
Step 1: Install Django and FastAPI
First, we need to install Django and FastAPI along with Uvicorn, an ASGI server used to run FastAPI applications.
pip install django fastapi uvicorn
Step 2: Create a Django Project
Start by creating a new Django project.
django-admin startproject myproject
cd myproject
Step 3: Create a Django App
Next, create a new Django app within the project.
python manage.py startapp myapp
Step 4: Configure Django Settings
In myproject/settings.py, add myapp to the INSTALLED_APPS list.
INSTALLED_APPS = [
...
'myapp',
]
File Structure

Building the Web Page
Step 5: Create a Django View
In myapp/views.py, create a view that renders an HTML page with the desired message.
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
Step 6: Create a URL Pattern
In myapp/urls.py, create a URL pattern for the view.
from django.urls import path
from .views import home
urlpatterns = [
path('', home, name='home'),
]
Update myproject/urls.py to include the app's URLs.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Step 7: Create an HTML Template
Create an HTML template in myapp/templates/home.html to display the message.
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
<style>
.welcome {
color: green;
}
</style>
</head>
<body>
<h1 class="welcome">Welcome to GeeksforGeeks</h1>
</body>
</html>
Integrating FastAPI
Step 8: Create FastAPI Endpoints
Create a new file myapp/fastapi.py and define some FastAPI endpoints.
from fastapi import FastAPI
app = FastAPI()
@app.get("/api/hello")
def read_root():
return {"message": "Hello from FastAPI"}
Step 9: Run FastAPI with Uvicorn
Run the FastAPI application using Uvicorn.
uvicorn myapp.fastapi:app --reload

Running the Django Server
Finally, run the Django development server.
python manage.py runserver

Conclusion
In this article, we combined Django and FastAPI to build a simple web application. We created a Django web page that displays "Welcome to GeeksforGeeks" in green color and integrated FastAPI to handle API endpoints. This combination leverages Django's robust web development features and FastAPI's modern API capabilities, providing a flexible and efficient solution for building web applications.