Project Workshop — URL Shortener API
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
FastAPI · SQLAlchemy async · Pydantic
Expected effort: 20–32 focused hours · Minimum meaningful tests: 12What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | @app.get/post/put/delete/patch decorators produces the specified behavior inside Path operations & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | path params + type validation produces the specified behavior inside Path operations & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | query params (optional/required/aliases) produces the specified behavior inside Path operations & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | APIRouter for modular routing produces the specified behavior inside Path operations & routing | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | BaseModel + Field() (min_length/max_length/ge/le/regex) produces the specified behavior inside Pydantic models | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | @field_validator (Pydantic v2) produces the specified behavior inside Pydantic models | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | model inheritance produces the specified behavior inside Pydantic models | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | from_attributes (orm_mode) produces the specified behavior inside Pydantic models | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.5 | nested models produces the specified behavior inside Pydantic models | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | Depends() + sub-dependencies produces the specified behavior inside Dependency injection | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | class-based dependencies produces the specified behavior inside Dependency injection | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | DB session yield pattern produces the specified behavior inside Dependency injection | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | current user dep with JWT produces the specified behavior inside Dependency injection | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.5 | Lifespan events produces the specified behavior inside Dependency injection | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | BackgroundTasks.add_task() produces the specified behavior inside Background tasks | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | async vs sync background tasks produces the specified behavior inside Background tasks | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | when to use Celery instead produces the specified behavior inside Background tasks | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | status codes and response_model produces the specified behavior inside HTTP & OpenAPI contract | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | OpenAPI schema generation and docs produces the specified behavior inside HTTP & OpenAPI contract | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | request body vs path/query/header/cookie parameters produces the specified behavior inside HTTP & OpenAPI contract | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | exception handlers and error schemas produces the specified behavior inside HTTP & OpenAPI contract | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── app/3│ ├── main.py4│ ├── api/{routes.py,dependencies.py}5│ ├── domain/{models.py,services.py,errors.py}6│ ├── repositories/7│ ├── schemas/8│ ├── workers/9│ └── observability.py10├── migrations/11├── tests/{unit,integration,contract}/12├── pyproject.toml13├── Dockerfile14└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Path operations & routing | @app.get/post/put/delete/patch decorators; path params + type validation; query params (optional/required/aliases) | Demonstration plus focused tests |
| 2 | Pydantic models | BaseModel + Field() (min_length/max_length/ge/le/regex); @field_validator (Pydantic v2); model inheritance | Demonstration plus focused tests |
| 3 | Dependency injection | Depends() + sub-dependencies; class-based dependencies; DB session yield pattern | Demonstration plus focused tests |
| 4 | Background tasks | BackgroundTasks.add_task(); async vs sync background tasks; when to use Celery instead | Demonstration plus focused tests |
| 5 | HTTP & OpenAPI contract | status codes and response_model; OpenAPI schema generation and docs; request body vs path/query/header/cookie parameters | Demonstration plus focused tests |
| 6 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
1from contextlib import asynccontextmanager2from fastapi import APIRouter, Depends, FastAPI, status3from pydantic import BaseModel, Field, HttpUrl4
5class LinkCreate(BaseModel):6 url: HttpUrl7 alias: str | None = Field(default=None, pattern=r"^[a-z0-9-]{4,32}$")8
9class LinkRead(BaseModel):10 code: str11 url: HttpUrl12
13router = APIRouter(prefix="/links", tags=["links"])14
15@router.post("", response_model=LinkRead, status_code=status.HTTP_201_CREATED)16async def create_link(body: LinkCreate, service=Depends(get_link_service)):17 return await service.create(body)18
19@asynccontextmanager20async def lifespan(app: FastAPI):21 app.state.http = build_http_client()22 yield23 await app.state.http.aclose()Expected result
1POST /links validates the URL and alias, resolves the service dependency, and returns 201.Code reading
| Line | Code | Explanation | |
|---|---|---|---|
| 1 | from contextlib import asynccontextmanager | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 2 | from fastapi import APIRouter, Depends, FastAPI, status | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 3 | from pydantic import BaseModel, Field, HttpUrl | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 5 | class LinkCreate(BaseModel): | Creates a class namespace and binds the resulting class object to this name. | |
| 6 | url: HttpUrl | Implements the next python statement in the example's data flow. | |
| 7 | `alias: str \ | None = Field(default=None, pattern=r"^[a-z0-9-]{4,32}$")` | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 9 | class LinkRead(BaseModel): | Creates a class namespace and binds the resulting class object to this name. | |
| 10 | code: str | Implements the next python statement in the example's data flow. | |
| 11 | url: HttpUrl | Implements the next python statement in the example's data flow. | |
| 13 | router = APIRouter(prefix="/links", tags=["links"]) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 15 | @router.post("", response_model=LinkRead, status_code=status.HTTP_201_CREATED) | Applies a decorator or framework annotation before the following definition is bound. | |
| 16 | async def create_link(body: LinkCreate, service=Depends(get_link_service)): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. | |
| 17 | return await service.create(body) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. | |
| 19 | @asynccontextmanager | Applies a decorator or framework annotation before the following definition is bound. | |
| 20 | async def lifespan(app: FastAPI): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. | |
| 21 | app.state.http = build_http_client() | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 22 | yield | Emits one lazy value and suspends the generator frame for a later resume. | |
| 23 | await app.state.http.aclose() | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Path operations & routing | A decorator registers the function; defining two identical method/path combinations silently creates an ambiguous or unreachable contract. | Group routes with APIRouter, order static paths before conflicting dynamic paths, and declare response models and status codes explicitly. |
| Pydantic models | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. | Separate create, update, internal, and public schemas. |
| Dependency injection | A generator dependency is a lifecycle boundary, not an ordinary lazy iterator; sharing sessions across requests or concurrent tasks corrupts transaction ownership. | Use dependencies for authentication, validated policy, units of work, and request resources; use lifespan state for process-wide clients and pools. |
| Background tasks | Returning a response does not guarantee an in-process background task completed. | Use BackgroundTasks for best-effort, short work and a durable queue for business-critical jobs. |
| HTTP & OpenAPI contract | Catching every exception and returning 200 or 400 erases retry semantics and hides defects from monitoring. | Define a small error envelope, map expected domain failures centrally, preserve causes in logs, and never expose stack traces or secrets to clients. |
Engineering checklist for this stack
- To do: authenticate before object lookup where possible
- To do: authorize the action and object server-side
- To do: keep transactions in the application service
- To do: bound request, response, and query work
- To do: map typed domain failures to stable protocol errors
Test strategy
Implement at least 12 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 4 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1@pytest.mark.anyio2async def test_duplicate_request_is_idempotent(client, auth_headers):3 headers = {**auth_headers, "Idempotency-Key": "stable-1"}4 first = await client.post("/resources", json={"name": "one"}, headers=headers)5 second = await client.post("/resources", json={"name": "one"}, headers=headers)6 assert first.status_code == 2017 assert second.status_code in {200, 201}8 assert first.json()["id"] == second.json()["id"]Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?