Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ __pycache__/

# C extensions
*.so
api/venv/
api/venv/
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"python-envs.defaultEnvManager": "ms-python.python:system",
"python-envs.pythonProjects": []
}
31 changes: 31 additions & 0 deletions api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from .database import get_db
import os
from dotenv import load_dotenv
import requests
from typing import Optional, Dict

load_dotenv()

Expand Down Expand Up @@ -68,3 +70,32 @@ def get_current_user(
if user is None:
raise credentials_exception
return user

def register_user(base_url: str, username: str, email: str, password: str) -> Optional[Dict]:
"""
Register a new user via the /register endpoint.

Args:
base_url (str): Base URL of the API,
username (str): Desired username
email (str): User email
password (str): User password

Returns:
dict: Response JSON from the server if successful, else None
"""
url = f"{base_url}/register"
payload = {
"username": username,
"email": email,
"password": password # plain password, server will hash
}
try:
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()
except requests.HTTPError as http_err:
print(f"HTTP error: {http_err} - {response.text}")
except Exception as err:
print(f"Other error: {err}")
return None
49 changes: 49 additions & 0 deletions api/clients/polls_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import requests

BASE_URL = "http://127.0.0.1:8000"
HEADERS = {"Authorization": "Bearer YOUR_TOKEN"}

def cast_vote(poll_id: int, option_id: int) -> dict:
"""
Cast a vote on an existing poll.

Args:
poll_id (int): The ID of the poll.
option_id (int): The ID of the option to vote for.

Returns:
dict: API response (success or failure).
"""
url = f"{BASE_URL}/polls/{poll_id}/vote"
payload = {"option_id": option_id}
response = requests.post(url, json=payload, headers=HEADERS)

try:
return response.json()
except ValueError:
return {"error": "Invalid response from server", "status_code": response.status_code}


def get_poll_results(poll_id: int) -> dict:
"""
Retrieve results of a poll.

Args:
poll_id (int): The ID of the poll.

Returns:
dict: Poll results following the API response schema.
"""
url = f"{BASE_URL}/polls/{poll_id}/results"
response = requests.get(url, headers=HEADERS)

try:
return response.json()
except ValueError:
return {"error": "Invalid response from server", "status_code": response.status_code}


if __name__ == "__main__":
results = get_poll_results(1) # 1 with = poll ID
if results:
print(results)
28 changes: 28 additions & 0 deletions api/polls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

import requests
from typing import Optional, Dict, List

def fetch_polls(base_url: str, skip: int = 0, limit: int = 10) -> Optional[List[Dict]]:
"""
Fetch paginated polls from the API.

Args:
base_url (str): Base URL of the API, e.g., "http://127.0.0.1:8000."
skip (int): Number of items to skip (for pagination)
limit (int): Maximum number of items to fetch

Returns:
List[Dict]: List of polls if successful, else None
"""
url = f"{base_url}/polls"
params = {"skip": skip, "limit": limit}

try:
response = requests.get(url, params=params)
response.raise_for_status()
return response.json() # Assuming the API returns a list of polls
except requests.HTTPError as http_err:
print(f"HTTP error: {http_err} - {response.text}")
except Exception as err:
print(f"Other error: {err}")
return None
26 changes: 24 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,32 @@
# main.py
from fastapi import FastAPI
from api.database import Base, engine
from api import models
from api.routes import router
from api.auth import register_user
from api.polls import fetch_polls

# Create tables
""" Create tables"""
Base.metadata.create_all(bind=engine)

app = FastAPI()
""" Initialize FastAPI app"""
app = FastAPI(title="Polly API")
app.include_router(router)

""" Constants"""
BASE_URL = "http://127.0.0.1:8000."


if __name__ == "__main__":
# Register a test user
result = register_user(BASE_URL, "alice", "alice@example.com", "SuperSecret123")
print("Register user result:", result)

""" Fetch first page of polls"""
polls = fetch_polls(BASE_URL, skip=0, limit=10)
if polls:
print("Fetched polls:")
for poll in polls:
print(poll)
else:
print("Failed to fetch polls")