Skip to content

HyperSkill academy project. Build a fun, interactive Python quiz chatbot from scratch. You'll create the chatbot's brain, connect it to a sleek web interface, and watch your Python knowledge grow. Get ready to dive into full-stack development with a project that's both educational and seriously engaging!

Notifications You must be signed in to change notification settings

ivansegrt/Cursors-Python-Quiz-Master

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Python Quiz Master - REST API

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.

πŸš€ Features

  • 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

πŸ“‹ Prerequisites

  • Python 3.8 or higher
  • pip (Python package manager)

πŸ› οΈ Installation

  1. Clone the repository (or navigate to the project directory)

  2. Install dependencies:

    pip install -r requirements.txt

πŸƒ Running the API

Development Server

python main.py

Or using uvicorn directly:

uvicorn main:app --reload --host 0.0.0.0 --port 8000

The 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

πŸ“š API Endpoints

Base Information

  • Root: GET / - API information and available endpoints
  • Health Check: GET /api/health - Check API status
  • Statistics: GET /api/stats - Get total number of questions

Questions Endpoints

Get All Questions

GET /api/questions

Response: 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 Specific Question

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 Random Question

GET /api/questions/random

Response: A randomly selected question (without correct answer)

Get Question with Details (Admin)

GET /api/questions/{question_id}/detail

Response: 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."
}

Quiz Endpoints

Submit Answer

POST /api/quiz/submit

Request 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 found
  • 422: Invalid answer format (must be a, b, c, or d)

πŸ’» Frontend Integration Examples

JavaScript/Fetch API

Get All Questions

fetch('http://localhost:8000/api/questions')
  .then(response => response.json())
  .then(questions => {
    console.log('Questions:', questions);
    // Display questions in your UI
  });

Get Random Question

fetch('http://localhost:8000/api/questions/random')
  .then(response => response.json())
  .then(question => {
    console.log('Random question:', question);
    // Display question to user
  });

Submit Answer

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');

React Example

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>
  );
}

πŸ”§ API Response Models

QuestionResponse

{
  id: number;
  question_text: string;
  options: string[];  // Array of 4 options
}

AnswerSubmitRequest

{
  question_id: number;  // 0-4
  answer: string;       // "a" | "b" | "c" | "d"
}

AnswerResponse

{
  is_correct: boolean;
  correct_answer: string;        // "a" | "b" | "c" | "d"
  correct_answer_text: string;   // The actual option text
  explanation: string;
}

🎯 Current Questions

The API includes 5 beginner-level Python questions covering:

  1. Python file extensions
  2. Function definition keywords
  3. Comment syntax
  4. Input function return types
  5. List syntax

πŸ”’ Security Notes

  • Questions are returned without correct answers by default
  • Correct answers are only revealed after submission via /api/quiz/submit
  • The /api/questions/{id}/detail endpoint includes answers (use with caution)
  • CORS is currently set to allow all origins (*) - restrict in production

πŸ“ Development

Running the Original CLI Chatbot

The original command-line chatbot is still available:

python chatbot.py

Project Structure

.
β”œβ”€β”€ main.py              # FastAPI application
β”œβ”€β”€ chatbot.py          # Original CLI chatbot (question data source)
β”œβ”€β”€ requirements.txt    # Python dependencies
└── README.md          # This file

πŸš€ Deployment

For production deployment:

  1. Update CORS settings in main.py:

    allow_origins=["https://your-frontend-domain.com"]
  2. Use a production ASGI server:

    uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
  3. Consider adding:

    • Authentication/authorization
    • Rate limiting
    • Database for questions (instead of hardcoded)
    • Session management for score tracking
    • HTTPS/SSL certificates

πŸ“– API Documentation

Interactive API documentation is available at:

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

🀝 Contributing

Feel free to add more questions by editing the build_questions() function in chatbot.py.

πŸ“„ License

This project is open source and available for educational purposes.

About

HyperSkill academy project. Build a fun, interactive Python quiz chatbot from scratch. You'll create the chatbot's brain, connect it to a sleek web interface, and watch your Python knowledge grow. Get ready to dive into full-stack development with a project that's both educational and seriously engaging!

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published