suhail commited on
Commit
14fdd05
·
1 Parent(s): 7ffe51d
Files changed (1) hide show
  1. README.md +23 -299
README.md CHANGED
@@ -1,309 +1,33 @@
1
- # Task CRUD API - Backend
 
 
 
 
 
 
 
 
2
 
3
- FastAPI backend for the Task Manager application with full CRUD operations, filtering, and sorting.
4
 
5
- ## Tech Stack
6
 
7
- - **Python**: 3.11+
8
- - **FastAPI**: 0.104+ (Web framework)
9
- - **SQLModel**: 0.0.14+ (ORM)
10
- - **Alembic**: 1.13.0 (Database migrations)
11
- - **PostgreSQL**: Neon Serverless or local PostgreSQL
12
- - **Pydantic**: 2.x (Data validation)
13
 
14
- ## Project Structure
 
 
 
15
 
16
- ```
17
- backend/
18
- ├── src/
19
- │ ├── api/
20
- │ │ ├── deps.py # Dependency injection (DB session, auth stub)
21
- │ │ └── routes/
22
- │ │ └── tasks.py # Task CRUD endpoints
23
- │ ├── core/
24
- │ │ ├── config.py # Application settings
25
- │ │ └── database.py # Database connection
26
- │ ├── models/
27
- │ │ ├── user.py # User model (stub)
28
- │ │ └── task.py # Task model
29
- │ ├── schemas/
30
- │ │ └── task.py # Pydantic schemas
31
- │ ├── services/
32
- │ │ └── task_service.py # Business logic
33
- │ └── main.py # FastAPI application
34
- ├── alembic/
35
- │ ├── versions/
36
- │ │ └── 001_initial.py # Initial migration
37
- │ └── env.py # Alembic configuration
38
- ├── tests/ # Test directory (to be implemented)
39
- ├── .env # Environment variables
40
- ├── .env.example # Environment template
41
- ├── alembic.ini # Alembic configuration
42
- └── requirements.txt # Python dependencies
43
- ```
44
 
45
- ## Setup Instructions
46
 
47
- ### 1. Install Dependencies
48
-
49
- ```bash
50
- cd backend
51
- pip install -r requirements.txt
52
- ```
53
-
54
- ### 2. Configure Environment
55
-
56
- Copy `.env.example` to `.env` and configure:
57
-
58
- ```bash
59
- cp .env.example .env
60
- ```
61
-
62
- Edit `.env`:
63
-
64
- ```env
65
- # For Neon PostgreSQL (recommended)
66
- DATABASE_URL=postgresql://user:password@ep-xxx.neon.tech/dbname?sslmode=require
67
-
68
- # OR for local PostgreSQL
69
- DATABASE_URL=postgresql://postgres:postgres@localhost:5432/todo_db
70
-
71
- APP_NAME=Task CRUD API
72
- DEBUG=True
73
- CORS_ORIGINS=http://localhost:3000
74
-
75
- # Authentication (REQUIRED)
76
- BETTER_AUTH_SECRET=<generate-32-char-random-string>
77
- JWT_ALGORITHM=HS256
78
- JWT_EXPIRATION_DAYS=7
79
- ```
80
-
81
- **Generate BETTER_AUTH_SECRET:**
82
- ```bash
83
- # Use Python to generate a secure random secret
84
- python -c "import secrets; print(secrets.token_urlsafe(32))"
85
-
86
- # IMPORTANT: Use the SAME secret in both backend/.env and frontend/.env.local
87
- ```
88
-
89
- ### 3. Run Database Migrations
90
-
91
- ```bash
92
- # Apply migrations to create tables
93
- python -m alembic upgrade head
94
- ```
95
-
96
- ### 4. Start Development Server
97
-
98
- ```bash
99
- # Start with auto-reload
100
- uvicorn src.main:app --reload
101
-
102
- # Server runs at http://localhost:8000
103
- ```
104
-
105
- ## API Endpoints
106
-
107
- ### Authentication
108
-
109
- | Method | Endpoint | Description | Auth Required |
110
- |--------|----------|-------------|---------------|
111
- | POST | `/api/auth/signup` | Register new user account | No |
112
- | POST | `/api/auth/signin` | Authenticate and receive JWT token | No |
113
- | GET | `/api/auth/me` | Get current user profile | Yes |
114
-
115
- ### Tasks
116
-
117
- | Method | Endpoint | Description | Auth Required |
118
- |--------|----------|-------------|---------------|
119
- | GET | `/api/tasks` | List tasks with filtering and sorting | Yes |
120
- | POST | `/api/tasks` | Create a new task | Yes |
121
- | GET | `/api/tasks/{id}` | Get a single task | Yes |
122
- | PUT | `/api/tasks/{id}` | Update task (replace all fields) | Yes |
123
- | PATCH | `/api/tasks/{id}` | Partially update task | Yes |
124
- | DELETE | `/api/tasks/{id}` | Delete a task | Yes |
125
-
126
- ### Query Parameters (GET /api/tasks)
127
-
128
- - `completed`: Filter by status (true/false/null for all)
129
- - `sort`: Sort field (created_at or updated_at)
130
- - `order`: Sort order (asc or desc)
131
- - `limit`: Maximum number of results
132
- - `offset`: Number of results to skip
133
-
134
- ### Example Requests
135
-
136
- **Sign Up:**
137
- ```bash
138
- curl -X POST http://localhost:8000/api/auth/signup \
139
- -H "Content-Type: application/json" \
140
- -d '{
141
- "email": "user@example.com",
142
- "password": "SecurePass123",
143
- "name": "John Doe"
144
- }'
145
- ```
146
-
147
- **Sign In:**
148
- ```bash
149
- curl -X POST http://localhost:8000/api/auth/signin \
150
- -H "Content-Type: application/json" \
151
- -d '{
152
- "email": "user@example.com",
153
- "password": "SecurePass123"
154
- }'
155
- ```
156
-
157
- **Get Current User (requires JWT token):**
158
- ```bash
159
- curl http://localhost:8000/api/auth/me \
160
- -H "Authorization: Bearer <your-jwt-token>"
161
- ```
162
-
163
- **Create Task (requires JWT token):**
164
- ```bash
165
- curl -X POST http://localhost:8000/api/tasks \
166
- -H "Content-Type: application/json" \
167
- -H "Authorization: Bearer <your-jwt-token>" \
168
- -d '{"title": "Buy groceries", "description": "Milk, eggs, bread"}'
169
- ```
170
-
171
- **List Active Tasks:**
172
- ```bash
173
- curl "http://localhost:8000/api/tasks?completed=false&sort=created_at&order=desc" \
174
- -H "Authorization: Bearer <your-jwt-token>"
175
- ```
176
-
177
- **Toggle Completion:**
178
- ```bash
179
- curl -X PATCH http://localhost:8000/api/tasks/1 \
180
- -H "Content-Type: application/json" \
181
- -H "Authorization: Bearer <your-jwt-token>" \
182
- -d '{"completed": true}'
183
- ```
184
 
185
  ## API Documentation
186
 
187
- Interactive API documentation available at:
188
- - **Swagger UI**: http://localhost:8000/docs
189
- - **ReDoc**: http://localhost:8000/redoc
190
-
191
- ## Database Schema
192
-
193
- ### Tasks Table
194
-
195
- | Column | Type | Description |
196
- |--------|------|-------------|
197
- | id | INTEGER | Primary key |
198
- | user_id | INTEGER | Foreign key to users |
199
- | title | VARCHAR(200) | Task title (required) |
200
- | description | VARCHAR(1000) | Task description (optional) |
201
- | completed | BOOLEAN | Completion status |
202
- | created_at | DATETIME | Creation timestamp |
203
- | updated_at | DATETIME | Last update timestamp |
204
-
205
- **Indexes:**
206
- - `ix_tasks_user_id` - User lookup
207
- - `ix_tasks_completed` - Status filtering
208
- - `ix_tasks_user_id_completed` - Combined user + status
209
- - `ix_tasks_created_at` - Date sorting
210
-
211
- ## Authentication
212
-
213
- **Status**: JWT-based authentication with Better Auth integration
214
-
215
- ### Authentication Flow
216
-
217
- 1. **User Registration** (`POST /api/auth/signup`):
218
- - Validates email format (RFC 5322)
219
- - Validates password strength (min 8 chars, uppercase, lowercase, number)
220
- - Hashes password with bcrypt (cost factor 12)
221
- - Creates user account in database
222
- - Returns user profile (no token issued)
223
-
224
- 2. **User Sign In** (`POST /api/auth/signin`):
225
- - Verifies email and password
226
- - Creates JWT token with 7-day expiration
227
- - Token includes: user_id (sub), email, issued_at (iat), expiration (exp)
228
- - Returns token and user profile
229
-
230
- 3. **Protected Endpoints**:
231
- - All `/api/tasks/*` endpoints require JWT authentication
232
- - Client must include `Authorization: Bearer <token>` header
233
- - Backend verifies token signature using `BETTER_AUTH_SECRET`
234
- - Extracts user_id from token and filters all queries by authenticated user
235
- - Returns 401 Unauthorized for missing, invalid, or expired tokens
236
-
237
- ### Security Features
238
-
239
- - **Stateless Authentication**: No server-side session storage
240
- - **User Data Isolation**: All task queries automatically filtered by authenticated user_id
241
- - **Password Security**: Bcrypt hashing with cost factor 12
242
- - **Token Expiration**: 7-day JWT expiration (configurable via JWT_EXPIRATION_DAYS)
243
- - **Shared Secret**: BETTER_AUTH_SECRET must match between frontend and backend
244
- - **Error Handling**: Generic error messages for invalid credentials (prevents user enumeration)
245
-
246
- ### Token Structure
247
-
248
- ```json
249
- {
250
- "sub": "123", // User ID
251
- "email": "user@example.com",
252
- "iat": 1704067200, // Issued at timestamp
253
- "exp": 1704672000, // Expiration timestamp (7 days)
254
- "iss": "better-auth" // Issuer
255
- }
256
- ```
257
-
258
- ### Error Responses
259
-
260
- - **401 TOKEN_EXPIRED**: JWT token has expired
261
- - **401 TOKEN_INVALID**: Invalid signature or malformed token
262
- - **401 TOKEN_MISSING**: No Authorization header provided
263
- - **401 INVALID_CREDENTIALS**: Email or password incorrect (generic message)
264
- - **409 EMAIL_EXISTS**: Email already registered during signup
265
-
266
- ## Development
267
-
268
- ### Create New Migration
269
-
270
- ```bash
271
- python -m alembic revision --autogenerate -m "description"
272
- ```
273
-
274
- ### Rollback Migration
275
-
276
- ```bash
277
- python -m alembic downgrade -1
278
- ```
279
-
280
- ### Run Tests (when implemented)
281
-
282
- ```bash
283
- pytest
284
- ```
285
-
286
- ## Troubleshooting
287
-
288
- ### Database Connection Issues
289
-
290
- 1. **Neon**: Ensure connection string includes `?sslmode=require`
291
- 2. **Local PostgreSQL**: Verify PostgreSQL is running and database exists
292
- 3. Check `.env` file has correct `DATABASE_URL`
293
-
294
- ### Migration Errors
295
-
296
- ```bash
297
- # Reset database (WARNING: deletes all data)
298
- python -m alembic downgrade base
299
- python -m alembic upgrade head
300
- ```
301
-
302
- ## Next Steps
303
-
304
- 1. Implement JWT authentication (Spec 2)
305
- 2. Add comprehensive test suite
306
- 3. Add API rate limiting
307
- 4. Implement pagination metadata
308
- 5. Add task categories/tags
309
- 6. Deploy to production (Vercel/Railway)
 
1
+ ---
2
+ title: TaskFlow API
3
+ emoji: ✅
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ license: mit
9
+ ---
10
 
11
+ # TaskFlow Backend API
12
 
13
+ FastAPI backend for TaskFlow task management application.
14
 
15
+ ## Features
 
 
 
 
 
16
 
17
+ - User authentication with JWT
18
+ - Task CRUD operations
19
+ - PostgreSQL database with SQLModel ORM
20
+ - RESTful API design
21
 
22
+ ## Environment Variables
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ Configure these in your Space settings:
25
 
26
+ - `DATABASE_URL`: PostgreSQL connection string
27
+ - `SECRET_KEY`: JWT secret key (generate a secure random string)
28
+ - `ALGORITHM`: JWT algorithm (default: HS256)
29
+ - `ACCESS_TOKEN_EXPIRE_MINUTES`: Token expiration time (default: 30)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  ## API Documentation
32
 
33
+ Once deployed, visit `/docs` for interactive API documentation.