feat: implement GraphQL member management API

Implement complete member management system with GraphQL API per OpenSpec proposal.
Only firstName is required; all other fields are optional with conditional validation.

Key features:
- GraphQL CRUD operations (create, read, update, delete members)
- SQLAlchemy 2.0 async with SQLite database
- Alembic database migrations
- Conditional validation (email/phone validated only when provided)
- Member fields: firstName (required), lastName, address, email, phone (all optional)
- Database seed script with sample member
- FastAPI with Strawberry GraphQL integration

Implementation details:
- Python 3.11+ with uv package manager
- Async database sessions throughout
- Proper error handling and validation
- Code quality: black, isort, ruff
- Comprehensive end-to-end testing completed

All 20 tasks from OpenSpec proposal completed successfully.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-20 12:21:13 +01:00
co-authored by Claude
parent f3f5e0282c
commit 1559c48104
22 changed files with 1897 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
# Database Configuration
DATABASE_URL=sqlite+aiosqlite:///./clubber.db
# Debug Mode
DEBUG=False
+33
View File
@@ -0,0 +1,33 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
*.egg-info/
dist/
build/
# Virtual environments
.venv/
venv/
ENV/
# Database
*.db
*.db-shm
*.db-wal
# Environment variables
.env
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
+1
View File
@@ -0,0 +1 @@
3.13
+148
View File
@@ -0,0 +1,148 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# sqlalchemy.url = driver://user:pass@localhost/dbname
# (URL configured programmatically in env.py from src.config)
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+91
View File
@@ -0,0 +1,91 @@
import asyncio
from logging.config import fileConfig
from alembic import context
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
# Import config to get database URL
from src.config import settings
# Import our Base and models
from src.database import Base
from src.models import member # noqa: F401 - import to register models
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Set the database URL from our settings
config.set_main_option("sqlalchemy.url", settings.database_url)
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# Set target_metadata to our Base metadata for autogenerate support
target_metadata = Base.metadata
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def do_run_migrations(connection: Connection) -> None:
"""Helper function to run migrations with a connection."""
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
"""Run migrations in 'online' mode with async support."""
connectable = async_engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
@@ -0,0 +1,57 @@
"""create members table
Revision ID: 0f79356844b5
Revises:
Create Date: 2025-11-20 11:39:25.900143
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "0f79356844b5"
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"members",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("first_name", sa.String(length=100), nullable=False),
sa.Column("last_name", sa.String(length=100), nullable=True),
sa.Column("street", sa.String(length=200), nullable=True),
sa.Column("apartment_number", sa.String(length=20), nullable=True),
sa.Column("zip", sa.String(length=20), nullable=True),
sa.Column("city", sa.String(length=100), nullable=True),
sa.Column("country", sa.String(length=100), nullable=True),
sa.Column("email", sa.String(length=255), nullable=True),
sa.Column("phone", sa.String(length=50), nullable=True),
sa.Column(
"created_at",
sa.DateTime(),
server_default=sa.text("(CURRENT_TIMESTAMP)"),
nullable=False,
),
sa.Column(
"updated_at",
sa.DateTime(),
server_default=sa.text("(CURRENT_TIMESTAMP)"),
nullable=False,
),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("members")
# ### end Alembic commands ###
+45
View File
@@ -0,0 +1,45 @@
[project]
name = "clubber"
version = "0.1.0"
description = "Member management system for non-profit societies with GraphQL API"
requires-python = ">=3.11"
authors = [
{ name = "Clubber Team" }
]
license = { text = "MIT" }
dependencies = [
"aiosqlite>=0.21.0",
"alembic>=1.17.2",
"fastapi>=0.121.3",
"pydantic-settings>=2.12.0",
"sqlalchemy[asyncio]>=2.0.44",
"strawberry-graphql[fastapi]>=0.286.0",
"uvicorn[standard]>=0.38.0",
]
[dependency-groups]
dev = [
"black>=25.11.0",
"isort>=7.0.0",
"pytest>=9.0.1",
"pytest-asyncio>=1.3.0",
"ruff>=0.14.5",
]
[tool.black]
line-length = 88
target-version = ["py311"]
[tool.ruff]
line-length = 88
[tool.ruff.lint]
select = ["E", "F", "W", "I"]
ignore = ["E501"]
[tool.isort]
profile = "black"
multi_line_output = 3
[tool.pytest.ini_options]
asyncio_mode = "auto"
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python
"""Seed database with sample member data."""
import asyncio
from sqlalchemy import select
from src.database import async_session_maker
from src.models.member import Member
async def seed_database():
"""Create sample member if it doesn't exist."""
async with async_session_maker() as session:
# Check if sample member already exists
result = await session.execute(
select(Member).where(Member.email == "jane.doe@example.com")
)
existing_member = result.scalar_one_or_none()
if existing_member:
print("✓ Sample member already exists")
print(f" ID: {existing_member.id}")
print(f" Name: {existing_member.first_name} {existing_member.last_name}")
print(f" Email: {existing_member.email}")
return
# Create sample member with minimal required data
# Demonstrates that only firstName is required
sample_member = Member(
first_name="Jane",
last_name="Doe",
email="jane.doe@example.com",
# All other fields (street, zip, city, country, phone) are None
)
session.add(sample_member)
await session.commit()
await session.refresh(sample_member)
print("✓ Sample member created successfully!")
print(f" ID: {sample_member.id}")
print(f" Name: {sample_member.first_name} {sample_member.last_name}")
print(f" Email: {sample_member.email}")
print(f" Created at: {sample_member.created_at}")
if __name__ == "__main__":
print("Seeding database...")
asyncio.run(seed_database())
print("Done!")
View File
+13
View File
@@ -0,0 +1,13 @@
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application settings with environment variable support."""
database_url: str = "sqlite+aiosqlite:///./clubber.db"
debug: bool = False
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
settings = Settings()
+39
View File
@@ -0,0 +1,39 @@
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from src.config import settings
# Create async engine
async_engine = create_async_engine(
settings.database_url,
echo=settings.debug,
future=True,
)
# Create async session factory
async_session_maker = async_sessionmaker(
async_engine,
class_=AsyncSession,
expire_on_commit=False,
)
# Declarative base for models
class Base(DeclarativeBase):
pass
# Dependency for FastAPI
async def get_db_session() -> AsyncGenerator[AsyncSession, None]:
"""Provide database session for FastAPI dependency injection."""
async with async_session_maker() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
+31
View File
@@ -0,0 +1,31 @@
import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
from src.resolvers.member import Mutation, Query
# Create Strawberry schema
schema = strawberry.Schema(query=Query, mutation=Mutation)
# Create GraphQL router
graphql_app = GraphQLRouter(schema)
# Create FastAPI app
app = FastAPI(
title="Clubber API",
description="Member management system for non-profit societies",
version="0.1.0",
)
# Mount GraphQL endpoint
app.include_router(graphql_app, prefix="/graphql")
@app.get("/")
async def root():
"""Root endpoint with API information."""
return {
"message": "Clubber API",
"graphql_endpoint": "/graphql",
"docs": "/docs",
}
+3
View File
@@ -0,0 +1,3 @@
from src.models.member import Member
__all__ = ["Member"]
+43
View File
@@ -0,0 +1,43 @@
from datetime import datetime
from typing import Optional
from sqlalchemy import String, func
from sqlalchemy.orm import Mapped, mapped_column
from src.database import Base
class Member(Base):
"""Member model for club/society management."""
__tablename__ = "members"
# Primary key
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
# Required field
first_name: Mapped[str] = mapped_column(String(100), nullable=False)
# Optional fields
last_name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
street: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
apartment_number: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
zip: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
city: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
country: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
email: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
phone: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
# Timestamps
created_at: Mapped[datetime] = mapped_column(
default=func.now(), server_default=func.now(), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
default=func.now(),
server_default=func.now(),
onupdate=func.now(),
nullable=False,
)
def __repr__(self) -> str:
return f"<Member(id={self.id}, first_name='{self.first_name}', last_name='{self.last_name}')>"
View File
+194
View File
@@ -0,0 +1,194 @@
from typing import List, Optional
import strawberry
from sqlalchemy import select
from src.database import async_session_maker
from src.models.member import Member as MemberModel
from src.schemas.member import CreateMemberInput, Member, UpdateMemberInput
from src.validation import validate_email, validate_first_name, validate_phone
class MemberNotFoundError(Exception):
"""Raised when a member is not found."""
pass
@strawberry.type
class Query:
@strawberry.field
async def member(self, id: int) -> Optional[Member]:
"""Get a single member by ID."""
async with async_session_maker() as session:
result = await session.execute(
select(MemberModel).where(MemberModel.id == id)
)
db_member = result.scalar_one_or_none()
if db_member is None:
return None
return Member(
id=db_member.id,
first_name=db_member.first_name,
last_name=db_member.last_name,
street=db_member.street,
apartment_number=db_member.apartment_number,
zip=db_member.zip,
city=db_member.city,
country=db_member.country,
email=db_member.email,
phone=db_member.phone,
created_at=db_member.created_at,
updated_at=db_member.updated_at,
)
@strawberry.field
async def members(self) -> List[Member]:
"""List all members sorted by last name (nulls last), then first name."""
async with async_session_maker() as session:
result = await session.execute(
select(MemberModel).order_by(
MemberModel.last_name.nulls_last(), MemberModel.first_name
)
)
db_members = result.scalars().all()
return [
Member(
id=m.id,
first_name=m.first_name,
last_name=m.last_name,
street=m.street,
apartment_number=m.apartment_number,
zip=m.zip,
city=m.city,
country=m.country,
email=m.email,
phone=m.phone,
created_at=m.created_at,
updated_at=m.updated_at,
)
for m in db_members
]
@strawberry.type
class Mutation:
@strawberry.mutation
async def create_member(self, input: CreateMemberInput) -> Member:
"""Create a new member with validation."""
# Validate required field
validate_first_name(input.first_name)
# Conditional validation (only if fields are provided)
validate_email(input.email)
validate_phone(input.phone)
async with async_session_maker() as session:
# Create new member
db_member = MemberModel(
first_name=input.first_name,
last_name=input.last_name,
street=input.street,
apartment_number=input.apartment_number,
zip=input.zip,
city=input.city,
country=input.country,
email=input.email,
phone=input.phone,
)
session.add(db_member)
await session.commit()
await session.refresh(db_member)
return Member(
id=db_member.id,
first_name=db_member.first_name,
last_name=db_member.last_name,
street=db_member.street,
apartment_number=db_member.apartment_number,
zip=db_member.zip,
city=db_member.city,
country=db_member.country,
email=db_member.email,
phone=db_member.phone,
created_at=db_member.created_at,
updated_at=db_member.updated_at,
)
@strawberry.mutation
async def update_member(self, input: UpdateMemberInput) -> Member:
"""Update an existing member."""
async with async_session_maker() as session:
# Get member
result = await session.execute(
select(MemberModel).where(MemberModel.id == input.id)
)
db_member = result.scalar_one_or_none()
if db_member is None:
raise MemberNotFoundError(f"Member with ID {input.id} not found")
# Validate if fields are being updated
if input.first_name is not None:
validate_first_name(input.first_name)
validate_email(input.email)
validate_phone(input.phone)
# Update fields if provided
if input.first_name is not None:
db_member.first_name = input.first_name
if input.last_name is not None:
db_member.last_name = input.last_name
if input.street is not None:
db_member.street = input.street
if input.apartment_number is not None:
db_member.apartment_number = input.apartment_number
if input.zip is not None:
db_member.zip = input.zip
if input.city is not None:
db_member.city = input.city
if input.country is not None:
db_member.country = input.country
if input.email is not None:
db_member.email = input.email
if input.phone is not None:
db_member.phone = input.phone
await session.commit()
await session.refresh(db_member)
return Member(
id=db_member.id,
first_name=db_member.first_name,
last_name=db_member.last_name,
street=db_member.street,
apartment_number=db_member.apartment_number,
zip=db_member.zip,
city=db_member.city,
country=db_member.country,
email=db_member.email,
phone=db_member.phone,
created_at=db_member.created_at,
updated_at=db_member.updated_at,
)
@strawberry.mutation
async def delete_member(self, id: int) -> bool:
"""Delete a member by ID."""
async with async_session_maker() as session:
result = await session.execute(
select(MemberModel).where(MemberModel.id == id)
)
db_member = result.scalar_one_or_none()
if db_member is None:
raise MemberNotFoundError(f"Member with ID {id} not found")
await session.delete(db_member)
await session.commit()
return True
View File
+53
View File
@@ -0,0 +1,53 @@
from datetime import datetime
from typing import Optional
import strawberry
@strawberry.type
class Member:
"""GraphQL Member type."""
id: int
first_name: str
last_name: Optional[str]
street: Optional[str]
apartment_number: Optional[str]
zip: Optional[str]
city: Optional[str]
country: Optional[str]
email: Optional[str]
phone: Optional[str]
created_at: datetime
updated_at: datetime
@strawberry.input
class CreateMemberInput:
"""Input type for creating a member - only firstName required."""
first_name: str
last_name: Optional[str] = None
street: Optional[str] = None
apartment_number: Optional[str] = None
zip: Optional[str] = None
city: Optional[str] = None
country: Optional[str] = None
email: Optional[str] = None
phone: Optional[str] = None
@strawberry.input
class UpdateMemberInput:
"""Input type for updating a member - all fields optional except id."""
id: int
first_name: Optional[str] = None
last_name: Optional[str] = None
street: Optional[str] = None
apartment_number: Optional[str] = None
zip: Optional[str] = None
city: Optional[str] = None
country: Optional[str] = None
email: Optional[str] = None
phone: Optional[str] = None
+33
View File
@@ -0,0 +1,33 @@
import re
from typing import Optional
class ValidationError(Exception):
"""Raised when input validation fails."""
pass
# Compiled regex patterns
EMAIL_PATTERN = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
PHONE_PATTERN = re.compile(r"^\+?[1-9]\d{1,14}$") # E.164 format
def validate_first_name(first_name: str) -> None:
"""Ensure firstName is provided and non-empty."""
if not first_name or first_name.strip() == "":
raise ValidationError("firstName cannot be empty")
def validate_email(email: Optional[str]) -> None:
"""Validate email format only if email is provided (not None or empty)."""
if email is not None and email != "":
if not EMAIL_PATTERN.match(email):
raise ValidationError(f"Invalid email format: {email}")
def validate_phone(phone: Optional[str]) -> None:
"""Validate phone format only if phone is provided (not None or empty)."""
if phone is not None and phone != "":
if not PHONE_PATTERN.match(phone):
raise ValidationError(f"Invalid phone format: {phone}")
Generated
+1029
View File
File diff suppressed because it is too large Load Diff