API Testing Guide for Beginners
What is an API?
An API (Application Programming Interface) is like a waiter in a restaurant: - You (the client) make a request for food (data) - The waiter (API) takes your order to the kitchen (your system) - The kitchen prepares the food (processes your request) - The waiter brings back your meal (returns the response)
Prerequisites
Before you can use the API, you need:
- Valid User Account - A registered account on the system
- Organization Membership - You must be a member of an organization with one of these roles:
- Admin - Full organization access
- Examiner - Can create and evaluate assessments
- Super Admin - Platform-wide access
- Active Status - Your organization membership must be active
Note: If you don't have an organization membership or appropriate role, contact your organization administrator to be added.
How to Run Your API
Step 1: Start Your Django Server
First, make sure your Django development server is running:
# Navigate to your project directory
cd /Users/ravi/Documents/education
# Start the Django server
python manage.py runserver
You should see something like:
Starting development server at https://preparebuddy.com/
Your API is now available at: https://preparebuddy.com/assessment/api/
Step 2: Check if API is Working
Open your web browser and go to:
https://preparebuddy.com/assessment/api/organizations/
If you see an error about authentication, that's good! It means the API is working but requires login.
Method 1: Testing with Your Web Browser (Easiest)
Login First
- Go to your main site:
https://preparebuddy.com/ - Login with your admin/examiner account
- Now try the API endpoints again
Test Authentication
Go to: https://preparebuddy.com/assessment/api/organizations/
You should see JSON data like:
{
"organizations": [
{
"id": 1,
"name": "Your Organization Name",
"role": "admin"
}
]
}
Method 2: Using Postman (Visual Tool)
Postman is a user-friendly tool for testing APIs:
Download and Install
- Go to https://www.postman.com/downloads/
- Download and install Postman
- Create a free account
Test Authentication
- Create a new request in Postman
- Set method to
POST - URL:
https://preparebuddy.com/assessment/api/auth/token/ - Go to "Body" tab → Select "raw" → Choose "JSON"
- Enter:
{
"username": "your_username",
"password": "your_password"
}
- Click "Send"
You should get a response with a token:
{
"success": true,
"message": "Authentication successful. Use the 'token' field value as your Bearer token for all API requests.",
"token": "abc123xyz789...",
"user_id": 1,
"username": "your_username",
"email": "your_email@example.com",
"organizations": [
{
"id": 1,
"name": "Your Organization",
"role": "admin"
}
]
}
Important: The token field contains your authentication token (session key). Use this value for all API requests.
Use the Token for Other Requests
- Create a new GET request
- URL:
https://preparebuddy.com/assessment/api/organizations/ - Go to "Headers" tab
- Add header:
Authorizationwith value:Bearer abc123xyz789...(use your actual token) - Click "Send"
Method 3: Using Python Script (Programmatic)
Create a simple test script:
# test_my_api.py
import requests
import json
# Your API base URL
BASE_URL = "https://preparebuddy.com/assessment/api"
class SimpleAPITester:
def __init__(self):
self.session = requests.Session()
self.token = None
def test_authentication(self, username, password):
"""Test login and get token"""
print("🔐 Testing Authentication...")
url = f"{BASE_URL}/auth/token/"
data = {
"username": username,
"password": password
}
response = self.session.post(url, json=data)
if response.status_code == 200:
result = response.json()
self.token = result['token']
print(f"✅ Success! Logged in as {result['username']}")
print(f"📄 Token: {self.token[:20]}...")
return result
else:
print(f"❌ Failed: {response.status_code} - {response.text}")
return None
def test_organizations(self):
"""Test getting organizations"""
print("\n🏢 Testing Organizations...")
url = f"{BASE_URL}/organizations/"
headers = {"Authorization": f"Bearer {self.token}"}
response = self.session.get(url, headers=headers)
if response.status_code == 200:
result = response.json()
print(f"✅ Found {len(result['organizations'])} organizations")
for org in result['organizations']:
print(f" - {org['name']} (Role: {org['role']})")
return result
else:
print(f"❌ Failed: {response.status_code} - {response.text}")
return None
def test_rubrics(self):
"""Test getting rubrics"""
print("\n📋 Testing Rubrics...")
url = f"{BASE_URL}/rubrics/"
headers = {"Authorization": f"Bearer {self.token}"}
response = self.session.get(url, headers=headers)
if response.status_code == 200:
result = response.json()
print(f"✅ Found {len(result['rubrics'])} rubrics")
for rubric in result['rubrics']:
print(f" - {rubric['name']} ({rubric['total_possible_points']} points)")
return result
else:
print(f"❌ Failed: {response.status_code} - {response.text}")
return None
def test_submit_feedback(self, org_id):
"""Test submitting feedback"""
print("\n📝 Testing Feedback Submission...")
url = f"{BASE_URL}/feedbacks/bulk/"
headers = {"Authorization": f"Bearer {self.token}"}
# Sample feedback data
data = {
"organization_id": org_id,
"feedbacks": [
{
"title": "Test Math Feedback",
"feedback_content": "Student demonstrates good understanding of algebraic concepts. The problem-solving approach is systematic. However, there are minor computational errors that need attention. Overall, strong foundation with room for improvement in accuracy.",
"teacher_name": "Dr. Test Teacher",
"teacher_experience_level": "experienced",
"assessment_type": "essay",
"student_level": "Undergraduate Year 2",
"subject_area": "Mathematics"
}
]
}
response = self.session.post(url, json=data, headers=headers)
if response.status_code == 201:
result = response.json()
print(f"✅ Successfully submitted {len(result['feedbacks'])} feedbacks")
for feedback in result['feedbacks']:
print(f" - ID: {feedback['id']}, Title: {feedback['title']}")
return result
else:
print(f"❌ Failed: {response.status_code} - {response.text}")
return None
def main():
"""Run all tests"""
print("🚀 Starting API Tests")
print("=" * 50)
tester = SimpleAPITester()
# Replace with your actual credentials
USERNAME = "your_username" # Change this!
PASSWORD = "your_password" # Change this!
# Test 1: Authentication
auth_result = tester.test_authentication(USERNAME, PASSWORD)
if not auth_result:
print("❌ Authentication failed. Please check your credentials.")
return
# Test 2: Organizations
org_result = tester.test_organizations()
if not org_result or not org_result['organizations']:
print("❌ No organizations found.")
return
# Test 3: Rubrics
rubric_result = tester.test_rubrics()
# Test 4: Submit Feedback
org_id = org_result['organizations'][0]['id']
feedback_result = tester.test_submit_feedback(org_id)
print("\n" + "=" * 50)
print("🎉 API Testing Complete!")
if __name__ == "__main__":
main()
To run this script:
# Install requests if you don't have it
pip install requests
# Update the USERNAME and PASSWORD in the script
# Then run:
python test_my_api.py
Method 4: Using curl (Command Line)
If you're comfortable with command line:
# Test authentication
curl -X POST https://preparebuddy.com/assessment/api/auth/token/ \
-H "Content-Type: application/json" \
-d '{"username": "your_username", "password": "your_password"}'
# Test organizations (replace YOUR_TOKEN with actual token)
curl -X GET https://preparebuddy.com/assessment/api/organizations/ \
-H "Authorization: Bearer YOUR_TOKEN"
Method 5: Django Test Suite (Developer Testing)
Run the automated tests I created:
# Run all API tests
python manage.py test assessment.test_api
# Run specific test
python manage.py test assessment.test_api.TeacherFeedbackAPITestCase.test_authentication_endpoint
# Run with verbose output
python manage.py test assessment.test_api -v 2
Complete Testing Workflow
Here's a step-by-step complete test:
1. Authentication
POST /assessment/api/auth/token/
{
"username": "your_username",
"password": "your_password"
}
2. Get Organizations
GET /assessment/api/organizations/
Headers: Authorization: Bearer YOUR_TOKEN
3. Get Rubrics
GET /assessment/api/rubrics/
Headers: Authorization: Bearer YOUR_TOKEN
4. Submit Feedbacks
POST /assessment/api/feedbacks/bulk/
Headers: Authorization: Bearer YOUR_TOKEN
{
"organization_id": 1,
"feedbacks": [
{
"title": "Test Feedback",
"feedback_content": "This is a test feedback...",
"teacher_name": "Dr. Test",
"teacher_experience_level": "experienced",
"assessment_type": "essay",
"student_level": "Undergraduate",
"subject_area": "Computer Science"
}
]
}
5. Create Batch Evaluation
POST /assessment/api/batches/create/
Headers: Authorization: Bearer YOUR_TOKEN
{
"name": "Test Batch",
"rubric_id": 1,
"organization_id": 1,
"feedback_ids": [1, 2, 3]
}
6. Run Evaluation
POST /assessment/api/batches/1/run/
Headers: Authorization: Bearer YOUR_TOKEN
7. Check Status
GET /assessment/api/batches/1/status/
Headers: Authorization: Bearer YOUR_TOKEN
8. Download Report
GET /assessment/api/batches/1/report/?format=csv
Headers: Authorization: Bearer YOUR_TOKEN
Troubleshooting Common Issues
1. "Authentication required" error (401)
Symptoms: {"error": "Authentication required"}
Causes: - No Bearer token in Authorization header - Token not provided or malformed - Not logged in via web interface
Solutions:
- Use the /assessment/api/auth/token/ endpoint to get a token
- Add header: Authorization: Bearer your_token_here
- Or login via web interface and use session cookies
2. "Access denied" error (403)
Symptoms: {"error": "Access denied. API access requires organization membership..."}
Causes: - User is not a member of any organization - User doesn't have admin, examiner, or super_admin role - Organization membership is not active
Solutions:
- Contact your organization administrator to add you to an organization
- Request admin or examiner role in your organization
- Verify your membership status at /qbank/organization/
- Check if your account needs activation
3. "Invalid credentials" error (401)
Symptoms: {"error": "Invalid credentials"}
Causes: - Wrong username or password - Account locked or inactive
Solutions: - Verify username and password are correct - Try logging in via web interface first - Reset password if needed
4. "Invalid JSON" error (400)
Symptoms: {"error": "Invalid JSON"}
Causes: - Malformed JSON in request body - Missing quotes or commas - Invalid escape sequences
Solutions: - Validate JSON using online validator (jsonlint.com) - Check for trailing commas - Ensure all strings are properly quoted
5. "Token expired" error (401)
Symptoms: {"error": "Token expired. Please login again."}
Causes: - Token (session) has expired (default: 4 hours) - Session was invalidated
Solutions: - Re-authenticate to get a new token - Store token securely and refresh before expiration
6. Server not responding
Symptoms: Connection refused or timeout
Causes: - Django server not running - Wrong URL or port - Firewall blocking connection
Solutions:
- Start Django server: python manage.py runserver 8080
- Verify URL: https://preparebuddy.com/assessment/api/
- Check firewall settings
7. "Method not allowed" error (405)
Symptoms: {"error": "Method not allowed"}
Causes: - Using wrong HTTP method (GET instead of POST, etc.)
Solutions: - Check API documentation for correct method - Verify Postman/curl command uses correct method
Next Steps
Once you've confirmed the API works: 1. Document your specific endpoints - Note which rubrics and organizations you'll use 2. Create client libraries - Build helpers for your most common operations 3. Set up monitoring - Track API usage and performance 4. Consider rate limiting - Protect your server from too many requests 5. Plan for production - Think about security, scaling, and deployment
Quick Reference Card
Base URL: https://preparebuddy.com/assessment/api/
Authentication: POST /auth/token/
Organizations: GET /organizations/
Rubrics: GET /rubrics/
Submit: POST /feedbacks/bulk/
Create Batch: POST /batches/create/
Run Batch: POST /batches/{id}/run/
Check Status: GET /batches/{id}/status/
Get Report: GET /batches/{id}/report/
Remember: Always test with small amounts of data first, then scale up once you're confident everything works!
