from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Book(BaseModel):
title: str
author: str
# Sample data
books_db = [
Book(title="The Catcher in the Rye", author="J.D. Salinger"),
Book(title="To Kill a Mockingbird", author="Harper Lee"),
Book(title="1984", author="George Orwell")
]
@app.get("/books/", response_model=List[Book])
async def get_books():
return books_db
@app.post("/books/", response_model=Book)
async def add_book(book: Book):
books_db.append(book)
return book
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)Python Code Snippet: Simple RESTful API with FastAPI
Related Posts
More content you might like
How to Build a Fullstack App with Flask and React
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activateNext, install Flask in your virtual environment:
التعامل مع JSON في JavaScript: قراءة البيانات وكتابتها
أحيانًا قد تواجه أخطاء أثناء تحويل JSON، سواء كان ذلك بسبب تنسيق غير صالح أو مشكلة أخرى. يمكنك استخدام try...catch لمعالجة الأخطاء.
const invalidJson = '{"name": "أحمد", "age": 30,'; // JSON غير مكتمل
try {
const person = JSON.parse(invalidJson);
console.log(person);
} catch (error) {
console.error("خطأ في تحويل JSON:", error.message);
}AJAX with JavaScript: A Practical Guide
In this case, if the URL is invalid or there’s a network issue, the error is caught, and a message is logged.
Here are some common use cases where AJAX can be effectively used:
Getting Started with Pydantic: Data Validation and Type Coercion in Python
Pydantic models are simple Python classes that inherit from pydantic.BaseModel. Here's how you can create a basic Pydantic model:
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
age: int
is_active: bool = TrueDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!