FastAPI App for Fetching Random User Data

  • Share this:

Code introduction


This function creates a FastAPI application that defines an asynchronous function `fetch_user`, which fetches random user data from the JSONPlaceholder API and returns it.


Technology Stack : FastAPI, Pydantic, httpx

Code Type : Web API

Code Difficulty : Intermediate


                
                    
def fetch_random_user_data():
    import fastapi
    from pydantic import BaseModel
    from typing import Optional
    import httpx

    class User(BaseModel):
        id: int
        name: str
        email: str
        address: Optional[str] = None

    @fastapi FastAPI()
    def main():
        async def fetch_user():
            async with httpx.AsyncClient() as client:
                response = await client.get("https://jsonplaceholder.typicode.com/users/1")
                return response.json()

        return fetch_user()