The Bloggo

Create your first python API using FastAPI in Minutes.

In the realm of Python web development, frameworks like Flask and Django have reigned supreme for building websites and APIs. But a new champion has emerged – FastAPI! Especially for APIs and machine learning projects, FastAPI offers a powerful and user-friendly approach.

This guide takes you by the hand, step-by-step, to create a basic API using FastAPI. We’ll focus on clarity and ease of use, so you can be up and running in no time.

Why Choose FastAPI?

FastAPI is gaining traction for several reasons. It’s compact, speedy, and has excellent support for Pydantic, making asynchronous programming more straightforward. While Flask and Django are still fantastic choices, FastAPI offers a more focused approach for API development.

What’s Pydantic and Why Does it Matter?

Before diving into FastAPI, let’s meet Pydantic, a game-changer for data modeling and type hinting. While Python is known for its flexibility, types are often inferred during code execution. Pydantic lets you define clear structures for your API data, keeping things organized and making data validation a breeze.

Think of Pydantic as a blueprint for your API’s data. It ensures that incoming requests have the correct format and information, preventing errors and making your code more robust.

Here’s a glimpse of a Pydantic model in action:

from pydantic import BaseModel

class PromptInput(BaseModel):
    model: str
    stream: bool
    prompt: str
    system: str
    options: dict

This model defines the expected structure for incoming API requests. FastAPI can then leverage this model to parse and validate the data.

Getting Started with FastAPI

FastAPI is known for its ease of use. Installation is as simple as:

pip install fastapi
pip install uvicorn

Uvicorn is an ASGI server that excels at handling asynchronous code, making it a perfect companion for FastAPI.

Now, let’s create an entry point for your API application. You can name this file anything you like, such as “main.py”. Inside this file, you’ll instantiate FastAPI:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/api/v1/hello")
def hello_world(request: Request):
    params = dict(request.query_params.items())
    return JSONResponse(content=params)

Here’s a breakdown of what’s happening:

  • We import the necessary libraries from FastAPI.
  • We create an instance of the FastAPI application.
  • The @app.get decorator defines a route for handling GET requests.
  • The hello_world function processes the request and returns a JSON response.

Running the API:

Use Uvicorn to run your API:

uvicorn --reload --port 5000 main:app

This command starts the Uvicorn server, watches for code changes (thanks to --reload), and exposes your app on port 5000.

Now, visit http://127.0.0.1:5000/api/v1/hello?say=Hi in your browser. You should see the JSON response:

{"say":"Hi"}

Voila! You’ve built a functional API in just a few lines of code.

Beyond JSON: Can FastAPI Handle HTML Too?

While FastAPI excels in the API world, for complex backend applications with templates, Django might be a better fit. However, you can still serve HTML content with FastAPI using Jinja2 templates. Here’s a quick example:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.get("/api/v1/hello", response_class=HTMLResponse)
def hello_world(request: Request):
    params = dict(request.query_params.items())
    return templates.TemplateResponse("hello.html", {"request": request, "params": params})

Authentication with FastAPI

FastAPI allows you to implement authentication logic using middleware. Here’s a basic example using token-based authentication:

from fastapi import FastAPI,Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

@app.middleware("http")
async def check_api_key_header(request: Request, call_next):
    api_key = request.headers.get("API-AUTH-TOKEN")
    if api_key != 'Some Secret':
        return JSONResponse(status_code=403, 
           content={"error": "Access Denied!"})

    response = await call_next(request)
    return response

@app.get("/api/v1/hello")
def hello_world(request: Request):
    params = dict(request.query_params.items())
    return templates.TemplateResponse("hello.html", 
       {"request": request, "params": params})

FastAPI vs. Django Rest Framework (DRF)

While Django Rest Framework (DRF) is a mature and comprehensive solution for building APIs, FastAPI offers a minimalist and performant alternative. FastAPI is particularly suitable for high-concurrency applications, microservices, machine learning APIs, or when you need efficient asynchronous support.

Is FastAPI Ready for Production?

Absolutely! Many developers and companies use FastAPI in production environments, handling large-scale applications efficiently. Its performance and scalability make it a preferred choice for modern web APIs.

Conclusion

FastAPI is a robust and efficient framework for building APIs in Python, offering ease of use, performance, and flexibility. Whether you’re developing small services or large-scale applications, FastAPI can be a valuable tool in your development arsenal.To dive deeper and start building your own APIs, explore the FastAPI documentation for comprehensive guides and resources.

Subscribe to Porto newsletter and stay updated.

Don’t miss anything. Get all the latest posts delivered straight to your inbox. It’s free!

Subscription Form
Scroll to Top