dogmadogmassage.com

Essential Insights on Python FastAPI You Should Know

Written on

Chapter 1: Introduction to FastAPI

FastAPI is a powerful framework for building APIs with Python, allowing developers to create a backend application with minimal setup.

FastAPI backend application overview

1. One-File Backend Application

Creating a simple backend app is straightforward with FastAPI. Here’s how you can do it:

from fastapi import FastAPI

app = FastAPI()

@app.get('/')

def home():

return {'message': 'hello world'}

import uvicorn

uvicorn.run(app)

After running this script, you can access it via your browser at localhost:8000/, which will return {"message": "hello world"}.

2. Accessing the /docs Endpoint

FastAPI automatically generates documentation for your API. To see it:

from fastapi import FastAPI

app = FastAPI()

@app.get('/')

def home():

return {'message': 'hello world'}

@app.get('/hello')

def hello():

return {'message': 'hello hello'}

import uvicorn

uvicorn.run(app)

By visiting localhost:8000/docs, you will find a Swagger UI that displays all your API endpoints, making it easy to test them during development.

3. Handling POST Requests with Pydantic

When creating a POST endpoint, it's essential to define the expected data types for the incoming payload. Here’s an example using Pydantic:

from fastapi import FastAPI

from pydantic import BaseModel

class MyPayload(BaseModel):

name: str

age: int

email: str

@app.post('/test')

def test(payload: MyPayload):

return {'payload': payload.dict(), 'status': 'ok'}

import uvicorn

uvicorn.run(app)

In this case, MyPayload is a class that defines the structure of the incoming data. This ensures that the data adheres to the specified types when making a POST request.

4. Uploading Files

FastAPI also allows you to upload files easily. Here’s how:

from fastapi import FastAPI, UploadFile

app = FastAPI()

@app.post('/upload_image')

def upload_image(images: list[UploadFile]):

print(images)

return {'status': 'ok'}

import uvicorn

uvicorn.run(app)

You can upload multiple files by specifying UploadFile in your POST request.

5. Distinguishing URL Parameters from Query Parameters

Understanding the difference between URL and query parameters is crucial:

  • URL parameters: http://localhost:8000/test/tom/40
  • Query parameters: http://localhost:8000/test?name=test&age=40

Both types serve unique purposes and can be utilized effectively within FastAPI.

6. Implementing Background Tasks

FastAPI supports background tasks, which can be scheduled to run periodically:

from fastapi import FastAPI

import asyncio

app = FastAPI()

x = [1] # global variable

@app.get('/x')

def get_x():

return {'x': x}

async def periodic():

while True:

x[0] += 1

print(f"x is now {x}")

await asyncio.sleep(2)

@app.on_event("startup")

async def start_periodic_task():

loop = asyncio.get_event_loop()

loop.create_task(periodic())

if __name__ == "__main__":

import uvicorn

uvicorn.run(app)

In this example, the periodic function increments the global variable x every two seconds.

7. Using Multiple Routers

As your application grows, managing everything in a single file can become cumbersome. Implementing multiple routers can simplify your codebase:

# app.py

from fastapi import FastAPI

app = FastAPI()

@app.get('/')

def home():

return {'msg': 'home'}

from b import myrouter

app.include_router(myrouter)

import uvicorn

uvicorn.run(app)

In another file, you can define additional routes:

# b.py

from fastapi import APIRouter

myrouter = APIRouter(prefix='/testing')

@myrouter.get('/')

def router_home():

return {'msg': 'myrouter home'}

@myrouter.get('/haha')

def router_haha():

return {'msg': 'myrouter haha'}

By using the APIRouter, you can keep your application organized and modular.

Conclusion

I hope this overview has been informative and clear. If you found this content helpful, consider supporting it by leaving feedback or sharing your thoughts. Your engagement is greatly appreciated!

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Crafting a Multi-Million Dollar Fintech Product: 5 Key Principles

Explore five essential principles for designing successful fintech products that engage users and drive innovation in the financial sector.

How to Embrace a More Fulfilling Life Today

Discover actionable steps to live a fulfilling life by taking charge of your daily routine instead of waiting for the perfect moment.

Unlock Your Writing Potential: Skills to Elevate Your Craft

Discover essential writing skills and techniques to enhance your craft and engage your audience effectively.

Creating a Better World: The Journey Towards Perfection

Explore how uniting for a common cause can help us tackle global issues and create a harmonious world.

Statistical Truths: Understanding the Manipulation of Numbers

Exploring the misuse of statistics in public discourse and the importance of critical thinking.

Remembering a Hero: The Legacy of Robert Short

A tribute to Robert Short, the first American pilot to sacrifice his life in the Chinese War of Resistance, highlighting his bravery and enduring legacy.

Unlocking the Power of Natural Luck Through Self-Alignment

Discover how to activate natural luck through alignment and acceptance of love in your life, leading to transformative experiences.

# Embracing Fear: Insights for Personal Growth and Confidence

Explore how confronting fear can lead to personal growth and self-confidence.