Published on August 04, 2024By DeveloperBreeze

Python Code Snippet: Simple RESTful API with FastAPI

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)

Comments

Please log in to leave a comment.

Continue Reading:

Various cURL Examples for API Interactions

Published on January 26, 2024

bash

JSON File Reading and Decoding

Published on January 26, 2024

php

Read JSON Data from a File

Published on January 26, 2024

python

Asynchronous Data Fetching in JavaScript using 'fetch'

Published on January 26, 2024

javascript

JSON Serialization and Deserialization

Published on January 26, 2024

python

Fetch JSON Data from API in JavaScript

Published on January 26, 2024

javascript

JavaScript Promise Example

Published on January 26, 2024

php

Tailwind Browser Mockup

Published on January 26, 2024

Simple and Clean Tailwind Buttons

Published on January 26, 2024

Tailwind Buttons with Arrow Icon

Published on January 26, 2024