Build FastAPI really fast !!

Part 2: Concepts needed to build routes

Krishna K
2 min readMay 13, 2022

The client facing part of a building an API is its endpoint. While defining an endpoints name router based on the data attributes it will deliver. endpoint should be clear and non-redundant to reduce any conflict with HTTP Client.

The most popular HTTP client is your browser itself (Firefox, Safari), once you run your app in the local IDE-it will show you an URL in the terminal. That is the endpoint to access your API.

You can build multiple endpoints in the same FastAPI using “Routes”. Each route is can bring in different set of datapoints from different data sources.

In this blog, I would highlight how to define a route and writing decorators.

Route processing http request

Routes:

To build routes in python, first you need to grasp concepts of decorators, functions, and annotations.

1. Decorators (@app):

Decorators take another function and enhances its ability without altering the function.

In below code snippet app.get is the decorator where the function say_hello is registered for the route /hello/{name}. {name} is the endpoint parameter.

When browser request for route /hello/{name} would be called and returns a result Hello {name}.

For example in the browser you can enter https://localhost:8000/hello/Dane would return Hello Dane .

@app.get("/hello/{name}")
async def say_hello(name: str):
return {"message": f"Hello {name}"}

2. Functions and annotations:

Knowing how to use If-else statements in a function is handy when building complex functions needed for FastAPI.

In the below example, you can see the function car_by_id take the id parameter from the router and checks if data requested is in database(db).

-> Represents the type the function car_by_id returns, in this example we expect the function returns a dictionary. If the data records requested by the api is present in the db (database), result[0] will return data records or else we get an HTTP Exception Error.

@app.get("/api/data/{id}")
def car_by_id(id: int) -> dict:
result = [car for car in db if car.id == id]
if result:
return result[0]
else:
raise HTTPException(status_code=400, detail=f"No car with id={id}.")

In my upcoming posts, will detail basic and advanced concepts in

Part 1: Getting started with FastAPI

Part 3: Creating GET, POST, PUT, DELETE requests

Part 4: Middleware & Azure application Insights

Part 5: Pydantic data models

Part 6: Define schemas

Part 7: Connect with SQL server to pull real-time data

Part 8: Secure your FastAPI & adding authentication

Part 9: Deploy using docker & AKS

Part 10: Bringing it all together

Thank you for reading !!

--

--

Krishna K
Krishna K

Written by Krishna K

Data Scientist, The World Bank. I blog about data science, machine learning, and building web apps & APIs.