YouTip LogoYouTip

Fastapi Route

## Introduction to FastAPI Routing In FastAPI, **routing** is the mechanism used to map incoming HTTP requests to specific Python functions. Each route defines an endpoint (a combination of an HTTP method and a URL path) and specifies how the application should process the request and return a response. FastAPI leverages Python type hints to automatically parse requests, validate data, and generate interactive API documentation (via Swagger UI and ReDoc) out of the box. --- ## Basic Routing To define a route in FastAPI, you decorate a Python function with an operation decorator from a `FastAPI` instance. ### The Root Route Here is how to create a FastAPI application instance and define a basic root route: ```python from fastapi import FastAPI # Create a FastAPI application instance app = FastAPI() # Define a route for the root path "/" using the HTTP GET method @app.get("/") def read_root(): return {"Hello": "World"} ``` #### Code Explanation: * `FastAPI()`: Initializes the main application object. * `@app.get("/")`: An operation decorator. It tells FastAPI that the function directly below it handles requests sent to the `/` path using the **GET** HTTP method. * `def read_root()`: The route handler function (or path operation function). When a client accesses the root URL, FastAPI executes this function and returns its result as a JSON response. --- ## Path and Query Parameters FastAPI allows you to capture dynamic values from the URL path (Path Parameters) as well as optional parameters appended to the URL (Query Parameters). ### Defining Parameters in Routes ```python from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} # Define a route with a path parameter {item_id} @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} ``` #### Code Explanation: * `@app.get("/items/{item_id}")`: The `{item_id}` syntax declares a **path parameter**. Its value is extracted from the URL and passed directly to the function argument of the same name. * `item_id: int`: By declaring the type hint as `int`, FastAPI automatically validates that the incoming path parameter is an integer. If a user visits `/items/foo`, FastAPI will automatically return a `422 Unprocessable Entity` validation error. * `q: str = None`: Since `q` is not part of the path template, FastAPI automatically interprets it as a **query parameter**. Setting its default value to `None` makes it optional. --- ## Running and Testing the Application ### 1. Start the Server You can run your FastAPI application using **Uvicorn**, a lightning-fast ASGI server. Run the following command in your terminal (assuming your Python file is named `main.py`): ```bash uvicorn main:app --reload ``` * `main:app`: Refers to the `main.py` file and the `app` instance of `FastAPI` created inside it. * `--reload`: Enables auto-reload, which automatically restarts the server whenever you make changes to your code. --- ### 2. Test the Endpoints #### Test the Root Route Open your browser and navigate to `http://127.0.0.1:8000`. You will see the JSON response: ```json { "Hello": "World" } ``` #### Test Path and Query Parameters Navigate to `http://127.0.0.1:8000/items/42?q=youtip`. FastAPI parses the path parameter `item_id` as `42` (converting it to an integer) and the query parameter `q` as `"youtip"`. The browser will display: ```json { "item_id": 42, "q": "youtip" } ``` --- ### 3. Interactive API Documentation One of FastAPI's most powerful features is the automatic generation of interactive documentation. While your server is running, visit: * **Swagger UI**: `http://127.0.0.1:8000/docs` * **ReDoc**: `http://127.0.0.1:8000/redoc` The Swagger UI allows you to visualize all your defined routes, inspect expected parameters, and test the endpoints directly from your web browser. --- ## Key Considerations 1. **Route Order Matters**: FastAPI evaluates routes sequentially from top to bottom. If you have a route `/items/all` and a route `/items/{item_id}`, place `/items/all` *above* the path parameter route. Otherwise, FastAPI will interpret `"all"` as an `item_id`. 2. **Automatic Type Conversion**: FastAPI automatically parses and converts incoming string inputs from URLs into the Python types specified in your function signatures (e.g., `int`, `float`, `bool`, `UUID`). 3. **Automatic Validation**: If a client sends invalid data (such as a string where an integer is expected), FastAPI returns a detailed JSON error response indicating exactly where the validation failed.
← Fastapi PydanticFastapi Step1 β†’