tinycodinglm / code /appdev-0030.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame
2.31 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

Walk me through building a rest api: key concepts, concrete details and common pitfalls. Include a runnable code example with its expected output.

Assistant

Bookshelf REST API:

python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional

app = FastAPI(title='Bookshelf API')

class Book(BaseModel):
    title: str
    author: str
    year: Optional[int] = None
    read: bool = False

books: dict[int, Book] = {}
next_id = 1

@app.get('/books')
def list_books():
    return [{'id': k, **v.model_dump()} for k, v in books.items()]

@app.get('/books/{book_id}')
def get_book(book_id: int):
    if book_id not in books:
        raise HTTPException(404, 'Book not found')
    return {'id': book_id, **books[book_id].model_dump()}

@app.post('/books', status_code=201)
def create_book(book: Book):
    global next_id
    books[next_id] = book
    result = {'id': next_id, **book.model_dump()}
    next_id += 1
    return result

@app.put('/books/{book_id}')
def update_book(book_id: int, book: Book):
    if book_id not in books:
        raise HTTPException(404, 'Book not found')
    books[book_id] = book
    return {'id': book_id, **book.model_dump()}

@app.delete('/books/{book_id}', status_code=204)
def delete_book(book_id: int):
    if book_id not in books:
        raise HTTPException(404, 'Book not found')
    del books[book_id]

# Run: uvicorn main:app --reload
# Docs: http://localhost:8000/docs

Features:

  • Automatic OpenAPI docs at /docs
  • Request validation via Pydantic
  • Type hints for IDE support
  • Async support with async def