How to use FastAPI routers in azure app functions

BERGES Armand 0 Reputation points
2024-10-11T13:26:22.8933333+00:00

I'm trying to use FastAPI within my Azure App function. I've followed the MS tutorial and finally come up with the following files :

function_app.py

import azure.functions as func

from fastapi_app.main import app as fastapi_app

app = func.AsgiFunctionApp(app=fastapi_app, http_auth_level=func.AuthLevel.FUNCTION)

fastapi_app.main module

import azure.functions as func

import fastapi

from fastapi_app.api_v1.api import router as api_router

app = fastapi.FastAPI()

@app.get("/sample")
async def index():
    return {
        "info": "Try /hello/Shivani for parameterized route.",
    }


@app.get("/hello/{name}")
async def get_name(name: str):
    return {
        "name": name,
    }

app.include_router(api_router, prefix="/api/v1")

api_router module

from fastapi import APIRouter

from fastapi_app.api_v1.endpoints import users

router = APIRouter()
router.include_router(users.router, prefix="/users", tags=["Users"])

users module

from fastapi import APIRouter

router = APIRouter()


@router.get("/")
async def root():
    return {"message": "Get Users!"}

This is a very simple app. When I'm running my app locally (with func host start) I'm able to make the following request sucessfully wget http://localhost:7071/sample or wget http://localhost:7071/hello/myName and obtain the correct output.

When I'm going to http://localhost:7071/api/v1/users in my browser, I'm able to find the right output.

However, when I'm running wget http://localhost:7071/api/v1/users I have an error that tells me that the underlying connection has been closed. I have the same kind of issues when my Azure function is deployed in Azure.

Because of that I'm guessing it should be an issue regarding the usage of FastAPI Router but I was unable to find anything that make it work.

Any help appreciated !

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
5,909 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Sina Salam 22,031 Reputation points Volunteer Moderator
    2024-10-11T16:24:30.6733333+00:00

    Hello BERGES Armand,

    Welcome to the Microsoft Q&A and thank you for posting your questions here.

    I understand that you would like to know how you can use FastAPI routers in azure app functions.

    The error (The underlying connection has been closed) suggests there may be a timeout or connection problem. So, you can try to set longer timeouts in your request or debugging this using Azure's logs and try to review the following settings and configurations:

    1. Check your function.json configuration is correct for the Azure Functions environment. If you don't have it already, you need to create a function.json file.
    2. If you use external tools like wget, you might run into CORS issues, so you have to add CORS middleware to your FastAPI app like the below:
    from fastapi.middleware.cors import CORSMiddleware
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # Adjust as necessary for security
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    1. Set your app to always be warm, it might be a cold start issue.
    2. Your routes are working fine for /sample and /hello/{name}, but you’re having trouble with /api/v1/users. Double-check that your FastAPI router setup is correct:

    In api_router:

    router.include_router(users.router, prefix="/users", tags=["Users"])
    
    1. After making these changes locally, redeploy your app to Azure Functions, and enable "Always On" if you're experiencing cold start issues on Azure.

    I hope this is helpful! Do not hesitate to let me know if you have any other questions.


    Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful.


  2. Pinaki Ghatak 5,600 Reputation points Microsoft Employee Volunteer Moderator
    2024-10-16T09:06:26.68+00:00

    Hello @BERGES Armand

    One thing to check is whether you have properly defined the users router in your api_router module. In your users module, you have defined a root endpoint with @router.get("/"), but you have not defined an endpoint for /api/v1/users.

    You should define an endpoint for /api/v1/users in your users module like this:

    @router.get("/api/v1/users") async def get_users(): 
    return {"message": "Get Users!"}
    

    Then, in your api_router module, you can include the users router with the prefix /api/v1/users like this:

    from fastapi import APIRouter
    from fastapi_app.api_v1.endpoints import users
    router = APIRouter() 
    router.include_router(users.router, prefix="/api/v1/users", tags=["Users"])
    

    With these changes, you should be able to access the /api/v1/users endpoint of your FastAPI app when running your Azure Function.


    I hope that this response has addressed your query and helped you overcome your challenges. If so, please mark this response as Answered. This will not only acknowledge our efforts, but also assist other community members who may be looking for similar solutions.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.