Mastering API Development with the FastAPI Framework

Mastering API Development with the FastAPI Framework

Let's Lean How to setup FastAPI

  • Install Python: If you don't have Python installed on your system, you can download it from the official Python website (https://www.python.org/downloads/).

  • Create a Virtual Environment: It's recommended to create a virtual environment for your FastAPI project to keep your dependencies isolated. You can use the built-in venv module in Python to create a virtual environment

      python -m venv myenv
    
  • Install FastAPI: With the virtual environment activated, install FastAPI and its dependencies using pip:

      pip install fastapi uvicorn
    
  • Create a FastAPI Application: Create a new Python file (e.g., main.py) and add the following code:

      from fastapi import FastAPI
      import uvicorn
      app = FastAPI()
    
      @app.get("/")
      async def root():
          return {"message": "Hello World"}
    
      if __name__ == "__main__":
          uvicorn.run(app, host="0.0.0.0", port=8000
    
  • Uvicorn is an ASGI web server implementation for Python to run FastApi app on local host

Let's create an api endpoint using FastApi

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Product(BaseModel):
    id: int
    name: str
    description: str
    price: float

@app.get("/") #endpoint
async def root():
    return {"message": "Welcome to the E-commerce API!"}


# example of dynamic url
@app.get("/products/{product_id}", response_model=Product) 
async def get_product(product_id: int):
    # Fetch the product data from a database or external service
    product = {
        "id": product_id,
        "name": "Product Name",
        "description": "Product Description",
        "price": 19.99
    }
    return product
  • To run the FastApi app use uvicorn main:app --reload command

      uvicorn main:app --reload
    

The api endpoint /product/{product_id} will return product based on the product_id provided in the params making it a dynamic url

Pydantic is data validation and parsing library generally used for data modelling of data that the user passes while hitting the api endpoint or when the user recieves the data when hitting the api endpoint.

HTTP methods used to create endpoints are GET,POST,PUT,DELETE

In the above example we have created get request api.

This way you can created api endpoints quickly and easily with the help of FastAPI

FastAPI also helps to document your api and you can access this docs using /docs endpoint of the FastAPI app.

Did you find this article valuable?

Support Ratish Jain by becoming a sponsor. Any amount is appreciated!