Final Project Exam: FPT Customer Chatbot - Backend API System#
overview#
Field |
Value |
|---|---|
Course |
Building Monolith API with FastAPI |
Project Name |
|
Duration |
360 minutes (6 hours) |
Passing Score |
70% |
Total Points |
100 |
Framework |
Python 3.10+, FastAPI, SQLAlchemy, SQLite, Pydantic, pytest |
Description#
You have been hired as a Backend Engineer at FPT Software, tasked with building the Backend API Layer for the FPT Customer Service Chatbot system.
This exam builds upon the AI Core developed in the LangGraph and Agentic AI module. Your task is to create a production-ready FastAPI backend that:
Provides REST API endpoints for the chatbot system
Implements database persistence with SQLAlchemy
Handles authentication and authorization
Integrates with the AI Core (from LangGraph module)
Implements proper error handling and logging
This exam assumes you have completed (or have access to) the AI Core from the LangGraph and Agentic AI module exam. You will integrate the AI agents with your FastAPI backend.
Objectives#
By completing this exam, you will demonstrate mastery of:
FastAPI Fundamentals: Building REST APIs with proper routing and request handling
Database Modeling: Designing and implementing SQLAlchemy models
CRUD Operations: Implementing Create, Read, Update, Delete operations
Dependency Injection: Using FastAPIβs dependency injection system
Authentication: Implementing JWT-based authentication
Input Validation: Using Pydantic for request/response validation
Error Handling: Implementing proper HTTP error responses
Unit Testing: Writing tests with pytest
Problem Description#
Build the Backend API for the FPT Customer Service Chatbot named fpt-customer-chatbot-api that includes:
Component |
Responsibilities |
|---|---|
Ticket API |
REST endpoints for support ticket CRUD operations |
Booking API |
REST endpoints for meeting room booking CRUD operations |
Chat API |
Endpoints to interact with the AI chatbot core |
User API |
User registration and authentication |
Database Layer |
SQLAlchemy models and database session management |
Prerequisites#
Completed FastAPI module assignments (recommended)
Python 3.10+ with virtual environment
SQLite (bundled with Python)
AI Core from LangGraph module (or mock implementation for standalone testing)
Technical Requirements#
Environment Setup#
Python 3.10 or higher
Required packages:
fastapi>= 0.100.0uvicorn>= 0.23.0sqlalchemy>= 2.0.0pydantic>= 2.0.0python-jose[cryptography]>= 3.3.0passlib[bcrypt]>= 1.7.0pytest>= 7.0.0httpx>= 0.24.0
Database Schema#
Implement the following tables using SQLAlchemy:
User Table:
Column |
Type |
Constraints |
|---|---|---|
id |
Integer |
Primary Key, Auto-increment |
String |
Unique, Required |
|
hashed_password |
String |
Required |
full_name |
String |
Required |
phone |
String |
Optional |
is_active |
Boolean |
Default: True |
created_at |
DateTime |
Auto-set |
Ticket Table:
Column |
Type |
Constraints |
|---|---|---|
id |
Integer |
Primary Key, Auto-increment |
ticket_id |
String |
Unique, Auto-generated UUID |
content |
String |
Required |
description |
Text |
Optional |
user_id |
Integer |
Foreign Key to User |
status |
Enum |
Pending/InProgress/Resolved/Canceled |
created_at |
DateTime |
Auto-set |
updated_at |
DateTime |
Auto-update |
Booking Table:
Column |
Type |
Constraints |
|---|---|---|
id |
Integer |
Primary Key, Auto-increment |
booking_id |
String |
Unique, Auto-generated UUID |
reason |
String |
Required |
time |
DateTime |
Required, must be future |
user_id |
Integer |
Foreign Key to User |
note |
Text |
Optional |
status |
Enum |
Scheduled/Finished/Canceled |
created_at |
DateTime |
Auto-set |
updated_at |
DateTime |
Auto-update |
Conversation Table:
Column |
Type |
Constraints |
|---|---|---|
id |
Integer |
Primary Key, Auto-increment |
conversation_id |
String |
Unique, Auto-generated UUID |
user_id |
Integer |
Foreign Key to User |
created_at |
DateTime |
Auto-set |
updated_at |
DateTime |
Auto-update |
Tasks#
Task 1: Project Setup & Database Models (15 points)#
Time Allocation: 60 minutes
Set up the FastAPI project structure and implement database models.
Requirements:#
Create project structure following FastAPI best practices
Implement SQLAlchemy models for all tables (User, Ticket, Booking, Conversation)
Create database session management with dependency injection
Implement Pydantic schemas for request/response validation
Set up Alembic migrations (optional but recommended)
Deliverables:#
models/directory with all SQLAlchemy modelsschemas/directory with all Pydantic schemasdatabase.py- Database connection and session managementconfig.py- Application configuration
Task 3: Ticket API Implementation (20 points)#
Time Allocation: 90 minutes
Implement full CRUD operations for support tickets.
Requirements:#
Create Ticket:
POST /api/v1/ticketsRequires authentication
Auto-generate ticket_id (UUID)
Set initial status to βPendingβ
List Tickets:
GET /api/v1/ticketsSupport pagination (skip, limit)
Filter by status (optional)
Return only userβs tickets
Get Ticket:
GET /api/v1/tickets/{ticket_id}Return 404 if not found
Ensure user owns the ticket
Update Ticket:
PUT /api/v1/tickets/{ticket_id}Allow status transitions only
Validate status transitions
Cancel Ticket:
DELETE /api/v1/tickets/{ticket_id}Soft delete (change status to Canceled)
Deliverables:#
routers/tickets.py- Ticket endpointscrud/tickets.py- Ticket CRUD operationsUnit tests for ticket endpoints
Task 4: Booking API Implementation (20 points)#
Time Allocation: 90 minutes
Implement full CRUD operations for meeting room bookings.
Requirements:#
Create Booking:
POST /api/v1/bookingsRequires authentication
Validate time is in the future
Auto-generate booking_id (UUID)
List Bookings:
GET /api/v1/bookingsSupport pagination
Filter by status and date range
Return only userβs bookings
Get Booking:
GET /api/v1/bookings/{booking_id}Return 404 if not found
Update Booking:
PUT /api/v1/bookings/{booking_id}Allow updates only for βScheduledβ bookings
Validate new time is in future
Cancel Booking:
DELETE /api/v1/bookings/{booking_id}Soft delete (change status to Canceled)
Deliverables:#
routers/bookings.py- Booking endpointscrud/bookings.py- Booking CRUD operationsUnit tests for booking endpoints
Task 5: Chat API & AI Integration (15 points)#
Time Allocation: 60 minutes
Create endpoints to interact with the AI chatbot core.
Requirements:#
Start Conversation:
POST /api/v1/chat/conversationsCreate new conversation record
Initialize AI graph with user context
Send Message:
POST /api/v1/chat/conversations/{conversation_id}/messagesForward message to AI core
Return AI response
Handle HITL interrupts
Confirm Action (for HITL):
POST /api/v1/chat/conversations/{conversation_id}/confirmResume interrupted operations
Accept βconfirmβ or βcancelβ
Get Conversation History:
GET /api/v1/chat/conversations/{conversation_id}Return all messages in conversation
If the AI Core is not available, implement mock responses that simulate the multi-agent behavior.
Deliverables:#
routers/chat.py- Chat endpointsservices/chat_service.py- AI integration serviceservices/ai_adapter.py- Adapter for AI Core (or mock)
Task 6: Error Handling & Testing (10 points)#
Time Allocation: 30 minutes
Implement proper error handling and write unit tests.
Requirements:#
Global Exception Handler:
Handle validation errors
Handle database errors
Return proper HTTP status codes
Custom Exceptions:
NotFoundException- 404 responsesUnauthorizedException- 401 responsesForbiddenException- 403 responses
Unit Tests:
Test all CRUD operations
Test authentication flow
Use pytest fixtures for database setup
Deliverables:#
utils/exceptions.py- Custom exception classestests/directory with all test filesTest coverage report
Test Scenarios#
Complete these test scenarios to demonstrate system functionality:
Scenario 1: User Registration & Authentication#
1. Register new user with email and password
2. Login with credentials
3. Access protected endpoint with JWT token
4. Verify 401 response without token
Scenario 2: Ticket Lifecycle#
1. Create a support ticket
2. List all user's tickets
3. Update ticket status to "InProgress"
4. Resolve the ticket
5. Verify status transitions
Scenario 3: Booking with Validation#
1. Attempt to book with past time β 400 error
2. Create valid booking for future time
3. Update booking time
4. Cancel the booking
5. Verify cannot update canceled booking
Scenario 4: Chat with AI (if integrated)#
1. Start new conversation
2. Send IT support query β AI responds
3. Request to create ticket β HITL interrupt
4. Confirm action β Ticket created in database
5. Verify ticket exists via Ticket API
Questions to Answer#
Include written responses to these questions in ANSWERS.md:
Database Design: Why did you choose this table structure? What are the trade-offs of using foreign keys for user_id?
Authentication: Explain the JWT token flow. What are the security considerations for token storage on the client side?
API Design: Why use UUIDs for ticket_id/booking_id instead of auto-increment IDs? What are the pros and cons?
Error Handling: How would you implement rate limiting for the API? What HTTP status code would you return?
Integration: Describe how you would deploy this API with the AI Core in a production environment. Consider: containerization, scaling, monitoring.
Submission Requirements#
Directory Structure#
fpt-customer-chatbot-api/
βββ routers/
β βββ auth.py
β βββ users.py
β βββ tickets.py
β βββ bookings.py
β βββ chat.py
βββ models/
β βββ user.py
β βββ ticket.py
β βββ booking.py
β βββ conversation.py
βββ schemas/
β βββ user.py
β βββ ticket.py
β βββ booking.py
β βββ chat.py
βββ crud/
β βββ users.py
β βββ tickets.py
β βββ bookings.py
βββ services/
β βββ chat_service.py
β βββ ai_adapter.py
βββ utils/
β βββ security.py
β βββ exceptions.py
βββ tests/
β βββ test_auth.py
β βββ test_tickets.py
β βββ test_bookings.py
β βββ conftest.py
βββ main.py
βββ database.py
βββ config.py
βββ dependencies.py
βββ requirements.txt
βββ README.md
βββ ANSWERS.md
Required Deliverables#
Complete source code following directory structure
README.mdwith:Setup instructions (environment, dependencies)
API documentation (or link to Swagger UI)
Notes on AI Core integration
ANSWERS.mdwith written responses to all 5 questionsrequirements.txtwith all dependenciesDemo video or screenshots showing:
User registration and login flow
Ticket CRUD operations
Booking CRUD operations
Chat with AI (if integrated)
Submission Checklist#
All code runs without errors
Database models properly defined
Authentication flow works
All CRUD endpoints functional
Input validation working
Error handling implemented
Unit tests passing
Documentation complete
Evaluation Criteria#
Criteria |
Points |
Excellent (100%) |
Good (75%) |
Needs Improvement (50%) |
|---|---|---|---|---|
Project Setup & Models (Task 1) |
15 |
Perfect structure, all models, proper schemas |
Working but minor issues in structure |
Basic setup, missing some models |
Authentication (Task 2) |
20 |
Complete auth flow with proper security |
Auth works but minor security gaps |
Basic auth without token validation |
Ticket API (Task 3) |
20 |
Full CRUD with validation and tests |
Most operations work, some validation missing |
Only 1-2 operations functional |
Booking API (Task 4) |
20 |
Full CRUD with time validation and tests |
Most operations work, time validation issues |
Only 1-2 operations functional |
Chat API & Integration (Task 5) |
15 |
Full integration with AI Core working |
Chat works with mock responses |
Basic endpoint without proper integration |
Error Handling & Testing (Task 6) |
10 |
Comprehensive error handling and 80%+ coverage |
Basic error handling and some tests |
Minimal error handling, few tests |
Total |
100 |
Hints#
Use
APIRouterfor organizing endpoints by resourceUse Pydanticβs
BaseModelfor all request/response schemasKeep database models separate from Pydantic schemas
Use
passlibwith bcrypt for password hashingUse
python-josefor JWT token creation/verificationStore secret key in environment variables
Use
Depends(get_db)for database session injectionConsider using
AsyncSessionfor better performanceUse
relationship()for foreign key relationships
Use
TestClientfrom FastAPI for endpoint testingCreate a separate test database
Use
pytest.fixturefor test setup/teardown
Create an adapter layer to abstract AI Core
Handle async operations properly
Implement proper error handling for AI failures