Add FastAPI as a component within project to enhance API performance and support asynchronous operations.
Instructions:
Install Dependencies
Install FastAPI and Uvicorn:
pip install fastapi uvicorn
Create FastAPI App
Inside your Django project, create a new directory called fastapi_app.
Inside fastapi_app/, create __init__.py and main.py.
main.py example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
async def hello():
return {"message": "Hello from FastAPI"}
Run FastAPI Locally (for testing)
In the terminal, navigate to the Django project directory and run:
uvicorn fastapi_app.main:app --reload --port 8001
Configure ASGI Application
Modify your Django project’s asgi.py to include FastAPI routing:
import os
from django.core.asgi import get_asgi_application
from fastapi_app.main import app as fastapi_app
from django.urls import path
from django.conf.urls import re_path
django_asgi_app = get_asgi_application()
from fastapi.middleware.asgi import ASGIApp
application = ASGIApp(
app=django_asgi_app,
lifespan=None,
sub_apps=[("/api/fastapi", fastapi_app)],
)
Update urls.py
Modify Django’s urls.py to include FastAPI routes:
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/fastapi/', include('fastapi_app.main')),
]
Add FastAPI Tests
Use httpx for testing FastAPI routes. Add the following to your tests:
import httpx
import pytest
@pytest.mark.asyncio
async def test_hello():
async with httpx.AsyncClient() as client:
response = await client.get("http://localhost:8001/hello")
assert response.status_code == 200
assert response.json() == {"message": "Hello from FastAPI"}
Update Dependencies
Make sure your Django project requirements reflect the new additions:
pip freeze > requirements.txt
Configure Deployment
Update your docker-compose.yml or deployment files to include Uvicorn alongside Django.
Task: Integrate FastAPI into the Project
Add FastAPI as a component within project to enhance API performance and support asynchronous operations.
Instructions:
Install Dependencies
Install FastAPI and Uvicorn:
Create FastAPI App
fastapi_app
.fastapi_app/
, create__init__.py
andmain.py
.main.py
example:Run FastAPI Locally (for testing)
In the terminal, navigate to the Django project directory and run:
Configure ASGI Application
Modify your Django project’s
asgi.py
to include FastAPI routing:Update
urls.py
Modify Django’s
urls.py
to include FastAPI routes:Add FastAPI Tests
Use
httpx
for testing FastAPI routes. Add the following to your tests:Update Dependencies
Make sure your Django project requirements reflect the new additions:
Configure Deployment
Update your
docker-compose.yml
or deployment files to include Uvicorn alongside Django.Deliverables:
/api/fastapi/hello
.