Skip to content

Commit 943fff7

Browse files
committed
updated readme.md
1 parent 4430934 commit 943fff7

1 file changed

Lines changed: 170 additions & 34 deletions

File tree

README.md

Lines changed: 170 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,12 @@ A FastAPI-based KYC (Know Your Customer) system that automatically extracts stru
7070
```
7171

7272
4. **Configure environment variables**
73-
Copy the example environment file:
73+
Copy the example environment file to create your `.env` file:
7474
```bash
7575
cp .env.example .env
7676
```
77-
Open the `.env` file and configure it with your own AWS credentials, PostgreSQL URL, and JWT secret.
77+
78+
**Important**: Update these values with your actual AWS credentials and database credentials for production use.
7879

7980
5. **Initialize the database**
8081
```bash
@@ -112,20 +113,46 @@ API documentation: `http://localhost:8000/docs`
112113

113114
## API Endpoints
114115

116+
### Health Check
117+
118+
**GET** `/`
119+
- Health check endpoint
120+
- **Returns**: `{"message": "FastAPI Image Upload Server"}`
121+
122+
### User Registration
123+
124+
**POST** `/register`
125+
- Register a new user account
126+
- **Body**:
127+
```json
128+
{
129+
"username": "your_username",
130+
"password": "your_password"
131+
}
132+
```
133+
- **Returns**: `{"message": "User created successfully"}`
134+
- **Status**: 201 (Created)
135+
115136
### Authentication
116137

117138
**POST** `/token`
118-
- Get JWT access token
119-
- **Body**: `username`, `password`
120-
- **Returns**: `access_token`, `token_type`
139+
- Get JWT access token for authenticated endpoints
140+
- **Body** (form data): `username`, `password`
141+
- **Returns**:
142+
```json
143+
{
144+
"access_token": "eyJhbGc...",
145+
"token_type": "bearer"
146+
}
147+
```
121148

122149
### KYC Document Upload
123150

124151
**POST** `/kyc/upload-id` (Requires authentication)
125152
- Upload and process a government ID document
153+
- **Headers**: `Authorization: Bearer <access_token>`
126154
- **Form Parameters**:
127-
- `user_id` (string): Unique user identifier
128-
- `file` (file): Image file (JPEG, PNG, WebP)
155+
- `file` (file): Image file (JPEG, PNG, WebP) - Max 5MB
129156
- **Returns**:
130157
```json
131158
{
@@ -139,23 +166,88 @@ API documentation: `http://localhost:8000/docs`
139166

140167
**GET** `/tasks/{task_id}` (Requires authentication)
141168
- Poll for KYC extraction results
142-
- **Returns**: Task status and extracted ID data
169+
- **Headers**: `Authorization: Bearer <access_token>`
170+
- **Returns**:
171+
```json
172+
{
173+
"task_id": "celery-task-uuid",
174+
"user_id": "username",
175+
"status": "SUCCESS|PENDING|FAILURE",
176+
"upload_timestamp": "2026-05-31T10:30:00",
177+
"extracted_fields": { ... }
178+
}
179+
```
180+
181+
### View User Task History
182+
183+
**GET** `/kyc/users/{user_id}/tasks` (Requires authentication)
184+
- Retrieve a history of all past KYC tasks and their extracted data for a specific user
185+
- **Headers**: `Authorization: Bearer <access_token>`
186+
- **Note**: Users can only view their own task history
187+
- **Returns**:
188+
```json
189+
{
190+
"user_id": "username",
191+
"tasks": [
192+
{
193+
"task_id": "...",
194+
"status": "SUCCESS|PENDING|FAILURE",
195+
"upload_timestamp": "...",
196+
"extracted_fields": { ... }
197+
}
198+
]
199+
}
200+
```
201+
202+
### Download Uploaded File
203+
204+
**GET** `/uploads/{filename}` (No authentication required)
205+
- Redirect to an S3 presigned URL for the requested file
206+
- **Note**: Presigned URL expires after 1 hour
207+
- **Response**: HTTP 302 redirect to S3 URL
143208

144209
## API Usage Example
145210

146211
```bash
147-
# Get token
212+
# Register a new user
213+
curl -X POST http://localhost:8000/register \
214+
-H "Content-Type: application/json" \
215+
-d '{"username": "myuser", "password": "securepassword"}'
216+
217+
# Login and get access token
148218
curl -X POST http://localhost:8000/token \
149219
-H "Content-Type: application/x-www-form-urlencoded" \
150-
-d "username=admin&password=secret"
220+
-d "username=myuser&password=securepassword"
221+
222+
# Save the token (example)
223+
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
151224

152-
# Upload ID document
225+
# Upload ID document for processing
153226
curl -X POST http://localhost:8000/kyc/upload-id \
154-
-H "Authorization: Bearer <access_token>" \
155-
-F "user_id=user123" \
156-
-F "file=@id_photo.jpg"
227+
-H "Authorization: Bearer $TOKEN" \
228+
-F "file=@/path/to/id_photo.jpg"
229+
230+
# Check task status
231+
curl -X GET http://localhost:8000/tasks/abc123def456 \
232+
-H "Authorization: Bearer $TOKEN"
233+
234+
# View all your past KYC tasks
235+
curl -X GET http://localhost:8000/kyc/users/myuser/tasks \
236+
-H "Authorization: Bearer $TOKEN"
237+
238+
# Get presigned URL for an uploaded file
239+
curl -X GET http://localhost:8000/uploads/filename.jpg
157240
```
158241

242+
## Security Considerations
243+
244+
- **Password Hashing**: All passwords are hashed using bcrypt before storage
245+
- **JWT Secrets**: Use a strong, randomly generated secret for `SECRET_KEY` in production
246+
- **S3 Presigned URLs**: Generated URLs expire after 1 hour by default
247+
- **HTTPS**: Use HTTPS in production (configure in reverse proxy/load balancer)
248+
- **Rate Limiting**: Consider adding rate limiting middleware for production deployments
249+
- **CORS**: Configure CORS settings in FastAPI for frontend integration
250+
159251
## Extracted Data Format
160252

161253
AWS Textract returns ID fields with the following structure:
@@ -187,43 +279,87 @@ AWS Textract returns ID fields with the following structure:
187279
- JPEG/JPG
188280
- PNG
189281
- WebP
282+
- Maximum file size: 5MB
283+
284+
### Task Status Values
285+
- `PENDING`: File uploaded, processing in queue
286+
- `SUCCESS`: Processing completed successfully, extracted data is available
287+
- `FAILURE`: Processing failed, check extracted_fields for error message
190288

191289
### AWS Textract Confidence Threshold
192-
Adjust confidence scoring in `services/ocr_service.py` to filter low-confidence extractions.
290+
Adjust confidence scoring in `services/ocr_service.py` to filter low-confidence extractions. By default, all extractions are returned with confidence scores for manual filtering.
291+
292+
## Troubleshooting
293+
294+
### Common Issues
295+
296+
**"Could not validate credentials" error**
297+
- Ensure your JWT token is valid and not expired (expires after 30 minutes)
298+
- Include the token in the Authorization header: `Authorization: Bearer <token>`
299+
300+
**"File too large" error**
301+
- Maximum file size is 5MB
302+
- Compress or resize your image and try again
303+
304+
**"Invalid file type" error**
305+
- Only JPEG, PNG, and WebP formats are supported
306+
- Convert your image to one of these formats
307+
308+
**S3 Connection Errors**
309+
- Verify AWS credentials are set in `.env`
310+
- Ensure the IAM user has S3 permissions
311+
- Check S3 bucket name is correct and exists
312+
313+
**Database Connection Errors**
314+
- Ensure PostgreSQL is running on the configured host/port
315+
- Check DATABASE_URL in `.env` is correct
316+
- Verify database credentials are correct
317+
318+
**Celery Worker Not Processing Tasks**
319+
- Ensure Redis is running on the configured REDIS_URL
320+
- Check worker logs: `celery -A worker worker --loglevel=debug`
321+
- Verify AWS Textract credentials are configured
193322

194323
## Development
195324

196325
### Running Tests
197326
```bash
198-
pytest tests/
199-
```
200-
201-
### Docker Deployment
202-
A `docker-compose.yml` is available for containerized deployment with PostgreSQL and Redis.
203-
204-
## Logging
327+
# Install test dependencies (if not already installed)
328+
pip install pytest httpx
205329

206-
Logs are output to stdout with timestamps and log levels. Configure logging level in `utils/logger.py`.
330+
# Run all tests
331+
PYTHONPATH=. pytest tests/ -v
207332

208-
## Security Notes
333+
# Run specific test file
334+
PYTHONPATH=. pytest tests/test_main.py -v
209335

210-
- **Authentication**: Uses securely hashed (bcrypt) database-backed user authentication.
211-
- **Environment Variables**: Store sensitive credentials in `.env` files (never commit to version control).
212-
- **S3 Permissions**: Restrict S3 bucket access using IAM policies.
213-
- **JWT Secret**: Use a strong, random secret key for JWT signing.
336+
# Run with coverage report
337+
PYTHONPATH=. pytest tests/ --cov=. --cov-report=html
338+
```
214339

215-
## Troubleshooting
340+
### Code Structure
216341

217-
- **S3 Upload Fails**: Check AWS credentials and bucket permissions
218-
- **Celery Tasks Not Processing**: Ensure Redis is running and Celery worker is active
219-
- **Database Connection Error**: Verify PostgreSQL connection string and that the database exists
220-
- **Textract Errors**: Ensure the image is clear and readable; check AWS Textract quotas
342+
- **main.py**: FastAPI application with all endpoint definitions
343+
- **worker.py**: Celery worker task definition for background OCR processing
344+
- **config.py**: Application settings and configuration using Pydantic
345+
- **db/database.py**: SQLAlchemy database setup and session management
346+
- **db/models.py**: SQLAlchemy ORM models for KYCTask and User
347+
- **services/ocr_service.py**: AWS Textract integration for ID document processing
348+
- **utils/auth.py**: JWT token creation and validation utilities
349+
- **utils/file_utils.py**: S3 file upload and image validation utilities
350+
- **utils/logger.py**: Structured logging configuration
351+
- **tests/conftest.py**: Pytest configuration and shared test fixtures
352+
- **tests/test_main.py**: API endpoint tests
221353

222354
## AWS Setup for Self-Hosting
355+
223356
If you are deploying this API for your own project, you will need to configure the following in your AWS account:
357+
224358
1. **S3 Bucket**: Create a private S3 bucket to store uploaded ID images and extracted JSON data.
225359
2. **IAM User**: Create an IAM User with Programmatic Access (Access Key & Secret Key).
226360
3. **IAM Permissions**: Attach the `AmazonS3FullAccess` and `AmazonTextractFullAccess` policies to your IAM user.
227361
4. Add the IAM credentials and Bucket name to your `.env` file.
228362

229-
.
363+
## Logging
364+
365+
Logs are output to stdout with timestamps and log levels. Configure logging level in `utils/logger.py`.

0 commit comments

Comments
 (0)