A small FastAPI backend API for a mini-blog, with JWT authentication, posts, comments, tests, and configurable SQLite/PostgreSQL database support.
- JWT authentication using
/register(user creation + token) and/token(OAuth2 form login) - Protected write endpoints
/postand/comment - Nested read via
GET /posts/{id}returning a post with its comments - Clean responses hiding internal database fields
- Configurable SQLite/PostgreSQL database support using SQLAlchemy Core tables
pip install -r requirements.txt
cp .env.example .env
uvicorn main:app --reload --env-file .envDATABASE_URL controls the database backend. SQLite is used by default when DATABASE_URL is not set. PostgreSQL can be used by setting DATABASE_URL to a PostgreSQL connection string.
python-multipart(included inrequirements.txt) is required for the OAuth2 form at/token.
POST /register
Content-Type: application/json
{
"username": "blue_caterpillar",
"password": "mushroom42"
}201 Created → returns an access token.
- Open
/docs - Click Authorize
- Enter
usernameandpassword
Swagger will attach the token automatically to subsequent requests.
POST /token
Content-Type: application/x-www-form-urlencoded
username=blue_caterpillar&password=mushroom42200 OK → returns an access token.
| Method | Path | Auth | Response |
|---|---|---|---|
POST |
/post |
✅ | 201 → UserPost |
GET |
/posts |
❌ | List[UserPost] |
GET |
/posts/{id} |
❌ | UserPostWithComments |
Example
{
"id": 1,
"body": "My first post",
"comments": [
{ "id": 1, "body": "Nice work!" }
]
}
| Method | Path | Auth | Response |
|---|---|---|---|
POST |
/comment |
✅ | 201 → CommentOut |
GET |
/post/{id}/comments |
❌ | List[CommentOut] |
Example
{ "id": 1, "body": "Nice work!" }
Foreign-key validation
POST /comment verifies that post_id exists in the posts table:
HTTP/1.1 404 Not Found
{ "detail": "Post not found" }
GET /health
Returns a simple liveness probe:
{ "status": "ok" }POST /_dev/reset → 204 No Content
Clears comments, then posts (guarded; requires maintainer account).
Use only on local/dev databases.
UserPost:{ id, body }CommentOut:{ id, body }UserPostWithComments:{ id, body, comments: CommentOut[] }
- Pagination:
GET /posts?limit=&skip=andGET /post/{id}/comments?limit=&skip=
- Open
/docsand Authorize with your credentials. - Create a post →
POST /post(201 Created). - Create a comment for that post →
POST /comment(201 Created). - Retrieve nested data →
GET /posts/{id}to see comments embedded.
Originally inspired by the Teclado FastAPI course.
Extended, debugged, and documented independently.
