Project-Stage-Academy / UA1244_beta

1 stars 0 forks source link

Integrate FastAPI into the Project #112

Open mehalyna opened 10 hours ago

mehalyna commented 10 hours ago

Task: Integrate FastAPI into the Project

Add FastAPI as a component within project to enhance API performance and support asynchronous operations.


Instructions:

  1. Install Dependencies
    Install FastAPI and Uvicorn:

    pip install fastapi uvicorn
  2. 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"}
  3. Run FastAPI Locally (for testing)
    In the terminal, navigate to the Django project directory and run:

    uvicorn fastapi_app.main:app --reload --port 8001
  4. 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)],
    )
  5. 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')),
    ]
  6. 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"}
  7. Update Dependencies
    Make sure your Django project requirements reflect the new additions:

    pip freeze > requirements.txt
  8. Configure Deployment
    Update your docker-compose.yml or deployment files to include Uvicorn alongside Django.


Deliverables:

Virtual4087 commented 9 hours ago

I would like to work on this