diff --git a/documentation/blog/2022-11-29-mui-tooltip.md b/documentation/blog/2022-11-29-mui-tooltip.md index 75f978fe573c..883401cc8ed5 100644 --- a/documentation/blog/2022-11-29-mui-tooltip.md +++ b/documentation/blog/2022-11-29-mui-tooltip.md @@ -4,7 +4,7 @@ description: We'll discover the Material UI Tooltip component with examples slug: material-ui-tooltip-component authors: doro_onome tags: [material-ui, react] -image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2022-11-29-mui-tooltip/social.png +image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2022-11-29-mui-tooltip/social-2.png hide_table_of_contents: false --- diff --git a/documentation/blog/2023-08-08-fast-api.md b/documentation/blog/2025-01-09-fast-api.md similarity index 81% rename from documentation/blog/2023-08-08-fast-api.md rename to documentation/blog/2025-01-09-fast-api.md index 7f1ba971a16b..d4eee07706e0 100644 --- a/documentation/blog/2023-08-08-fast-api.md +++ b/documentation/blog/2025-01-09-fast-api.md @@ -4,10 +4,12 @@ description: We'll be looking at FastAPI, a modern Python microframework that si slug: introduction-to-fast-api authors: obisike_treause tags: [dev-tools] -image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-08-07-fast-api/social.png +image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2023-08-07-fast-api/social-2.png hide_table_of_contents: false --- +**This article was last updated on January 9, 2025, to include sections on Error Handling in FastAPI and Optimizing FastAPI Performance, with practical examples and simplified explanations for better understanding.** + ## Introduction Since its introduction to backend development, Python has grown in popularity, competing with pre-existing heavyweights such as [PHP](https://www.php.net/) and [.Net](https://dotnet.microsoft.com/en-us/languages). It has made the developer experience more efficient and streamlined by introducing simplicity and power. Despite being known to be slower than its counterpart, Python has thrived greatly in this ecosystem. @@ -326,6 +328,176 @@ Add the [utility functions](https://github.com/Otrex/refine-fastapi/blob/main/sr Following that, you can run the server to test the endpoints via the documentation. +## FastAPI: Error Handling + +Error handling in FastAPI is quite straightforward and intuitive. FastAPI provides an in-built class called HTTPException which makes it very easy to return proper error responses if something goes wrong. + +The following is an example that uses HTTPException for handling invalid inputs: + +#### Handling Invalid IDs + +```python +from fastapi import FastAPI, HTTPException + +app = FastAPI() + +@app.get("/items/{item_id}") +async def read_item(item_id: int): + if item_id <= 0: + # Raise an error if the item_id is invalid + raise HTTPException( + status_code=400, + detail="Invalid ID. ID must be greater than 0." + ) + return {"item_id": item_id} +``` + +This would be the response when the request sent by the user has item_id less than or equal to 0: + +```json +{ + "detail": "Invalid ID. ID must be greater than 0." +} +``` + +#### Customizing Error Responses + +You can also personalize the error response to include more information: + +```python +@app.get("/users/{user_id}") +async def read_user(user_id: int): + if user_id > 100: + raise HTTPException( + status_code=404, + detail={'error': 'User not found', 'user_id': user_id} + ) + return {"user_id": user_id} +``` + +The response for an invalid user ID might look like this: + +```json +{ + "error": "User not found", + "user_id": 150 +} +``` + +#### Catching Server Errors + +For unexpected errors, use the following exception handlers: + +```python +from fastapi import Request +from fastapi.responses import JSONResponse + +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + return JSONResponse( + status_code=500, + content={"message": "An unexpected error occurred. Please try again."} + ) +``` + +This ensures that should something fail on the server, the user will get a friendly error message. + +5. Optimizing Performance in FastAPI + +FastAPI is fast by default, but some things you can do will further increase the speed. Here are a few tips and code examples: + +#### Use Asynchronous Libraries + +Use async libraries like httpx for HTTP requests that don't block. + +```python +import httpx +from fastapi import FastAPI + +app = FastAPI() + +@app.get("/data") +async def get_data(): + async with httpx.AsyncClient() as client: + response = await client.get("https://api.example.com/data") + return response.json() +``` + +#### Implement Caching + +Caching reduces the number of database calls or API calls a server makes repeatedly; cache the responses using tools like Redis. + +```python +import aioredis +from fastapi import FastAPI + +app = FastAPI() +redis = aioredis.from_url("redis://localhost") + +@app.get("/items/{item_id}") +async def read_item(item_id: int): + # Check if item is cached + cached_item = await redis.get(f"item:{item_id}") + if cached_item: + return {"item": cached_item.decode("utf-8")} + + # Simulate database fetch + item = f"Item {item_id}" + await redis.set(f"item:{item_id}", item) + return {"item": item} +``` + +#### Use Load Balancer + +Configure a load balancer like Nginx or Traefik to do the heavy lifting on requests. A typical example might be this inside an Nginx config file: + +```nginx +server { + listen 80; + + location / { + proxy_pass http://127.0.0.1:8000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + } +} +``` + +#### Improve Query Performance + +Proper indexing of your database and avoiding fetching the data which isn't required. + +```python +from sqlalchemy.orm import Session +from fastapi import Depends + +@app.get("/users") +async def get_users(limit: int = 10, db: Session = Depends(get_db)): + return db.query(User).limit(limit).all() +``` + +#### Gzip Compression + +Enable Gzip compression in order to reduce response size: + +```bash +pip install fastapi-compression +``` + +Then, add it to your FastAPI app: + +```python +from fastapi import FastAPI +from fastapi_compression import CompressionMiddleware + +app = FastAPI() +app.add_middleware(CompressionMiddleware) +``` + +Follow these tips, and your FastAPI application will be fast and efficient, ready for high loads. + ## Advanced Concepts in FastAPI APIs are usually not basic, like the inventory API created. Sometimes, you'll need to persist data or validate credentials before performing requests or handling files. @@ -513,6 +685,16 @@ Starlette offers several other types of responses, including the **FileResponse* The source code for this inventory API can be found [here](https://github.com/Otrex/refine-fastapi). +## Comparison Table + +| **Feature** | **FastAPI** | **Django** | **Flask** | **Pyramid** | +| -------------------- | --------------------------- | ------------------------- | --------------------------- | --------------------------- | +| Performance | High (ASGI & async/await) | Moderate | Moderate | Moderate | +| Auto Documentation | Yes (Swagger/OpenAPI) | No | No | No | +| Database Integration | Requires external libraries | Built-in ORM (Django ORM) | Requires external libraries | Requires external libraries | +| Scalability | High | High | Moderate | High | +| Learning Curve | Easy | Moderate | Easy | Moderate | + ## Conclusion Congratulations on making it this far! By now, you should have gained valuable insight into using FastAPI to build your backend application. FastAPI is an exceptional, user-friendly, and highly effective API development tool. It provides the flexibility associated with a microframework and delivers exceptional performance, making it an excellent choice for your API development requirements.