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:

Empowering Creators: How FinTech is Reshaping the Economy

Explore how FinTech is transforming the creator economy by addressing its unique financial needs and challenges.

The Vital Role of Human Input in Data Annotation

Exploring the indispensable human touch in data annotation amidst AI advancements.

Understanding the Pendulum: A Simple Argument Against Flat Earth

Explore the pendulum's behavior and its implications for the flat Earth theory.

A Philosophical Exploration of the End of the World

An exploration of the theoretical implications of black holes and their potential impact on existence.

Urgent Alert for Shiba Inu Community: Beware of Scams!

The Shiba Inu community faces urgent warnings regarding scams targeting their investments. Stay informed and protect your assets.

Essential Heart Health Supplements You Should Always Maintain

Discover four vital heart health supplements that you should consistently take for optimal heart function and well-being.

# Letting Go: Embracing Change in Freelance Writing

A reflection on the importance of letting go in freelance writing to adapt to changing landscapes and find new opportunities.

Challenging Views on Sobriety: My Five Controversial Opinions

In this article, I share five controversial opinions on sobriety that may spark debate and reflection.