diff --git a/.gitignore b/.gitignore index 8a1755b..ecec04f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ __pycache__/ # C extensions *.so +api/venv/ +api/venv/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..ba2a6c0 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "python-envs.defaultEnvManager": "ms-python.python:system", + "python-envs.pythonProjects": [] +} \ No newline at end of file diff --git a/api/auth.py b/api/auth.py index 8a0f1f8..97adff8 100644 --- a/api/auth.py +++ b/api/auth.py @@ -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() @@ -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 \ No newline at end of file diff --git a/api/clients/polls_client.py b/api/clients/polls_client.py new file mode 100644 index 0000000..c46e38e --- /dev/null +++ b/api/clients/polls_client.py @@ -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) \ No newline at end of file diff --git a/api/polls.py b/api/polls.py new file mode 100644 index 0000000..4a4a650 --- /dev/null +++ b/api/polls.py @@ -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 diff --git a/main.py b/main.py index e1b496d..e2516b7 100644 --- a/main.py +++ b/main.py @@ -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")