Skip to content

Instantly share code, notes, and snippets.

@jfjensen
Created October 18, 2023 11:25
Show Gist options
  • Save jfjensen/420cb161a3e4e5138a2073b8e08e5870 to your computer and use it in GitHub Desktop.
Save jfjensen/420cb161a3e4e5138a2073b8e08e5870 to your computer and use it in GitHub Desktop.
An example application that manages a simple in-memory database of books using Litestar for Python
from __future__ import annotations
from dataclasses import dataclass
from litestar import Litestar, post, get, patch, put
from litestar.dto import DataclassDTO, DTOConfig, DTOData
from litestar.exceptions import HTTPException
@dataclass
class Book:
title: str
author: str
publisher: str
genre: str
book_id: int
BOOKS_DB = {}
BOOK_IX = 1
class ReadDTO(DataclassDTO[Book]):
config = DTOConfig()
class WriteDTO(DataclassDTO[Book]):
config = DTOConfig(exclude={"book_id"})
class PatchDTO(DataclassDTO[Book]):
config = DTOConfig(exclude={"book_id"}, partial=True)
@get(path="/books", sync_to_thread=False)
def get_books() -> dict:
return BOOKS_DB
@get(path="/book/{book_id:int}", return_dto=ReadDTO, sync_to_thread=False)
def get_book(book_id: int) -> Book:
book = BOOKS_DB.get(book_id, False)
if not(book):
raise HTTPException(status_code=400, detail=f"book with id [{book_id}] not found")
return book
@post(path="/book", dto=WriteDTO, return_dto=ReadDTO, sync_to_thread=False)
def create_book(data: DTOData[Book]) -> Book:
global BOOK_IX
new_book = data.create_instance(book_id=BOOK_IX)
BOOK_IX += 1
book_id = new_book.book_id
BOOKS_DB[book_id] = new_book
return new_book
@put(path="/book/{book_id:int}", dto=WriteDTO, return_dto=ReadDTO, sync_to_thread=False)
def update_book(book_id: int, data: DTOData[Book]) -> Book:
book = BOOKS_DB.get(book_id, False)
if not(book):
raise HTTPException(status_code=400, detail=f"book with id [{book_id}] not found")
data.update_instance(book)
return book
@patch(path="/book/{book_id:int}", dto=PatchDTO, return_dto=ReadDTO, sync_to_thread=False)
def partial_update_book(book_id: int, data: DTOData[Book]) -> Book:
book = BOOKS_DB.get(book_id, False)
if not(book):
raise HTTPException(status_code=400, detail=f"book with id [{book_id}] not found")
data.update_instance(book)
return book
app = Litestar(route_handlers=[create_book, get_book, get_books, partial_update_book, update_book])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment