A FastAPI-based REST API for a Python beginner-level quiz application. This API provides endpoints for retrieving quiz questions and submitting answers, designed for frontend integration.
- RESTful API built with FastAPI
- 5 Beginner-level Python questions covering fundamentals
- CORS enabled for frontend integration
- Automatic API documentation via Swagger UI
- Type-safe request/response models with Pydantic
- Stateless design - perfect for frontend state management
- Python 3.8 or higher
- pip (Python package manager)
-
Clone the repository (or navigate to the project directory)
-
Install dependencies:
pip install -r requirements.txt
python main.pyOr using uvicorn directly:
uvicorn main:app --reload --host 0.0.0.0 --port 8000The API will be available at:
- API Base URL:
http://localhost:8000 - Interactive API Docs (Swagger):
http://localhost:8000/docs - Alternative API Docs (ReDoc):
http://localhost:8000/redoc
- Root:
GET /- API information and available endpoints - Health Check:
GET /api/health- Check API status - Statistics:
GET /api/stats- Get total number of questions
GET /api/questionsResponse: List of all questions (without correct answers)
[
{
"id": 0,
"question_text": "What is the correct file extension for Python files?",
"options": [".pyt", ".pt", ".py", ".python"]
},
...
]GET /api/questions/{question_id}Parameters:
question_id(path, integer): Zero-based index (0-4)
Response: Single question (without correct answer)
{
"id": 0,
"question_text": "What is the correct file extension for Python files?",
"options": [".pyt", ".pt", ".py", ".python"]
}GET /api/questions/randomResponse: A randomly selected question (without correct answer)
GET /api/questions/{question_id}/detailResponse: Question with correct answer and explanation
{
"id": 0,
"question_text": "What is the correct file extension for Python files?",
"options": [".pyt", ".pt", ".py", ".python"],
"correct_option_key": "c",
"explanation": ".py is the standard extension for Python source files."
}POST /api/quiz/submitRequest Body:
{
"question_id": 0,
"answer": "c"
}Response:
{
"is_correct": true,
"correct_answer": "c",
"correct_answer_text": ".py",
"explanation": ".py is the standard extension for Python source files."
}Error Responses:
404: Question ID not found422: Invalid answer format (must be a, b, c, or d)
fetch('http://localhost:8000/api/questions')
.then(response => response.json())
.then(questions => {
console.log('Questions:', questions);
// Display questions in your UI
});fetch('http://localhost:8000/api/questions/random')
.then(response => response.json())
.then(question => {
console.log('Random question:', question);
// Display question to user
});const submitAnswer = async (questionId, selectedAnswer) => {
const response = await fetch('http://localhost:8000/api/quiz/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
question_id: questionId,
answer: selectedAnswer
})
});
const result = await response.json();
if (result.is_correct) {
console.log('Correct!', result.explanation);
} else {
console.log('Incorrect. Correct answer:', result.correct_answer);
console.log('Explanation:', result.explanation);
}
return result;
};
// Usage
submitAnswer(0, 'c');import { useState, useEffect } from 'react';
function QuizComponent() {
const [question, setQuestion] = useState(null);
const [selectedAnswer, setSelectedAnswer] = useState('');
const [result, setResult] = useState(null);
const [score, setScore] = useState({ correct: 0, total: 0 });
useEffect(() => {
fetchRandomQuestion();
}, []);
const fetchRandomQuestion = async () => {
const response = await fetch('http://localhost:8000/api/questions/random');
const data = await response.json();
setQuestion(data);
setSelectedAnswer('');
setResult(null);
};
const handleSubmit = async () => {
if (!selectedAnswer) return;
const response = await fetch('http://localhost:8000/api/quiz/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question_id: question.id,
answer: selectedAnswer
})
});
const data = await response.json();
setResult(data);
setScore(prev => ({
correct: prev.correct + (data.is_correct ? 1 : 0),
total: prev.total + 1
}));
};
return (
<div>
{question && (
<>
<h2>{question.question_text}</h2>
{question.options.map((option, idx) => (
<button
key={idx}
onClick={() => setSelectedAnswer(['a', 'b', 'c', 'd'][idx])}
disabled={!!result}
>
{['a', 'b', 'c', 'd'][idx]}) {option}
</button>
))}
<button onClick={handleSubmit} disabled={!selectedAnswer || !!result}>
Submit
</button>
{result && (
<div>
<p>{result.is_correct ? 'β
Correct!' : 'β Incorrect'}</p>
<p>{result.explanation}</p>
<p>Score: {score.correct}/{score.total}</p>
<button onClick={fetchRandomQuestion}>Next Question</button>
</div>
)}
</>
)}
</div>
);
}{
id: number;
question_text: string;
options: string[]; // Array of 4 options
}{
question_id: number; // 0-4
answer: string; // "a" | "b" | "c" | "d"
}{
is_correct: boolean;
correct_answer: string; // "a" | "b" | "c" | "d"
correct_answer_text: string; // The actual option text
explanation: string;
}The API includes 5 beginner-level Python questions covering:
- Python file extensions
- Function definition keywords
- Comment syntax
- Input function return types
- List syntax
- Questions are returned without correct answers by default
- Correct answers are only revealed after submission via
/api/quiz/submit - The
/api/questions/{id}/detailendpoint includes answers (use with caution) - CORS is currently set to allow all origins (
*) - restrict in production
The original command-line chatbot is still available:
python chatbot.py.
βββ main.py # FastAPI application
βββ chatbot.py # Original CLI chatbot (question data source)
βββ requirements.txt # Python dependencies
βββ README.md # This file
For production deployment:
-
Update CORS settings in
main.py:allow_origins=["https://your-frontend-domain.com"]
-
Use a production ASGI server:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
-
Consider adding:
- Authentication/authorization
- Rate limiting
- Database for questions (instead of hardcoded)
- Session management for score tracking
- HTTPS/SSL certificates
Interactive API documentation is available at:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
Feel free to add more questions by editing the build_questions() function in chatbot.py.
This project is open source and available for educational purposes.