Building an API with FastAPI: A Practical Guide for Indian Devs
Namaste, fellow devs! Today, I’m excited to share with you my experience of building an API with FastAPI, a modern Python web framework that’s taken the dev world by storm. As an Indian developer, I’ve had the chance to work with various frameworks and technologies, but FastAPI has been a game-changer for me.
So, what is FastAPI, and why should you care? FastAPI is a full-featured, high-performance framework that allows you to build scalable APIs quickly and easily. It’s built on top of standard Python type hints, which means you can leverage the power of Python’s static type checking system to ensure your code is robust and maintainable.
One of the things that impressed me most about FastAPI is its ease of use. As a seasoned developer, I was surprised by how quickly I was able to build a functional API with FastAPI. The framework comes with a rich set of features, including support for async/await syntax, automatic API documentation, and integration with popular databases.
Setting Up FastAPI
To get started with FastAPI, you’ll need to install the framework using pip:
pip install fastapi
Next, create a new file called main.py and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get(”/”)
async def read_root():
return {“Hello”: “World!”}
This code creates a new FastAPI app and defines a single route for the root URL. When you run the app using uvicorn (a popular ASGI server), you can access the API at http://localhost:8000/.
Adding Endpoints and Data Models
FastAPI makes it easy to add endpoints and data models to your API. Here’s an example of how you can add a new endpoint that returns a list of books: from fastapi import FastAPI, HTTPException from pydantic import BaseModel
app = FastAPI()
class Book(BaseModel): title: str author: str
@app.get(“/books/”) async def read_books(): return [{“title”: “Book 1”, “author”: “Author 1”}, {“title”: “Book 2”, “author”: “Author 2”}]
@app.get(“/books/{book_id}”)
async def read_book(book_id: int):
return {“title”: “Book 3”, “author”: “Author 3”}
This code defines a new data model called Book using Pydantic, which is a popular library for building robust data models in Python. The read_books and read_book endpoints use the Book model to return a list of books and a single book, respectively.
Deployment and Security
FastAPI makes it easy to deploy your API to a production environment. Here’s an example of how you can deploy your API to a cloud platform like AWS:
uvicorn main:app —host 0.0.0.0 —port 8000 —reload
This code tells uvicorn to start the app on port 8000 and reload the app automatically when code changes are detected.
FastAPI also provides built-in support for authentication and authorization, which is essential for securing your API. Here’s an example of how you can add authentication using JWT tokens: from fastapi import FastAPI, HTTPException from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=“token”)
@app.post(“/token”) async def login(form_data: dict = Form(…)): username = form_data.get(“username”) password = form_data.get(“password”) # Authenticate the user… return {“access_token”: “your_token_here”}
@app.get(“/protected”)
async def protected_route(token: str = Depends(oauth2_scheme)):
return {“Hello”: “World!”}
This code defines a new endpoint called token that returns a JWT token when the user logs in successfully. The protected_route endpoint uses the oauth2_scheme to authenticate the user and return a protected response.
So, my fellow devs, I hope this guide has been helpful in showing you the power and ease of use of FastAPI. What’s your experience with FastAPI? Have you built a scalable API using this framework? Share your stories in the comments below!
(Note: The code examples are simplified for illustration purposes only. In a real-world scenario, you should consider additional security measures, error handling, and testing.)
Share this post
Team Ruflo
Building AI products for Indian developers and small businesses. Bootstrapped, profitable, and obsessed with solving real problems.
More posts