File size: 2,309 Bytes
3c88a0f | 1 2 3 4 5 | {"type": "session", "harness": "opencode", "id": "appdev-0030", "name": "rest api"}
{"type": "message", "message": {"role": "system", "content": "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."}}
{"type": "message", "message": {"role": "user", "content": "Walk me through building a rest api: key concepts, concrete details and common pitfalls. Include a runnable code example with its expected output."}}
{"type": "message", "message": {"role": "assistant", "content": "**Bookshelf REST API:**\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel\nfrom typing import Optional\n\napp = FastAPI(title='Bookshelf API')\n\nclass Book(BaseModel):\n title: str\n author: str\n year: Optional[int] = None\n read: bool = False\n\nbooks: dict[int, Book] = {}\nnext_id = 1\n\n@app.get('/books')\ndef list_books():\n return [{'id': k, **v.model_dump()} for k, v in books.items()]\n\n@app.get('/books/{book_id}')\ndef get_book(book_id: int):\n if book_id not in books:\n raise HTTPException(404, 'Book not found')\n return {'id': book_id, **books[book_id].model_dump()}\n\n@app.post('/books', status_code=201)\ndef create_book(book: Book):\n global next_id\n books[next_id] = book\n result = {'id': next_id, **book.model_dump()}\n next_id += 1\n return result\n\n@app.put('/books/{book_id}')\ndef update_book(book_id: int, book: Book):\n if book_id not in books:\n raise HTTPException(404, 'Book not found')\n books[book_id] = book\n return {'id': book_id, **book.model_dump()}\n\n@app.delete('/books/{book_id}', status_code=204)\ndef delete_book(book_id: int):\n if book_id not in books:\n raise HTTPException(404, 'Book not found')\n del books[book_id]\n\n# Run: uvicorn main:app --reload\n# Docs: http://localhost:8000/docs\n```\n\n**Features:**\n- Automatic OpenAPI docs at `/docs`\n- Request validation via Pydantic\n- Type hints for IDE support\n- Async support with `async def`"}}
|