Project Workshop — Blog API → GraphQL
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
Django · Graphene · DataLoader
Expected effort: 45–72 focused hours · Minimum meaningful tests: 20What 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 | graphene.ObjectType/Schema/List/NonNull produces the specified behavior inside Graphene schema | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | resolve_fieldname methods produces the specified behavior inside Graphene schema | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | Interface/Union/custom scalars produces the specified behavior inside Graphene schema | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | DjangoObjectType: model binding/fields/exclude produces the specified behavior inside Graphene-Django | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | DjangoListField and DjangoFilterConnectionField produces the specified behavior inside Graphene-Django | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | N+1 problem with query count produces the specified behavior inside DataLoader for N+1 | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | promise library in Python produces the specified behavior inside DataLoader for N+1 | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | DataLoader batch_load_fn pattern produces the specified behavior inside DataLoader for N+1 | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | per-request DataLoader instances produces the specified behavior inside DataLoader for N+1 | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | Query class and resolve methods produces the specified behavior inside Queries, mutations & tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | Mutation Arguments and InputObjectType produces the specified behavior inside Queries, mutations & tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | payload errors vs raised GraphQLError produces the specified behavior inside Queries, mutations & tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | graphene.test.Client execute with variables/context produces the specified behavior inside Queries, mutations & tests | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── manage.py3├── config/{settings,urls,asgi,celery}.py4├── domain/5│ ├── models.py6│ ├── services.py7│ ├── selectors.py8│ ├── serializers-or-schema.py9│ ├── views-or-resolvers.py10│ ├── permissions.py11│ ├── tasks.py12│ └── consumers.py13├── templates/14├── tests/{unit,api,integration}/15├── pyproject.toml16└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Graphene schema | graphene.ObjectType/Schema/List/NonNull; resolve_fieldname methods; Interface/Union/custom scalars | Demonstration plus focused tests |
| 2 | Graphene-Django | DjangoObjectType: model binding/fields/exclude; DjangoListField and DjangoFilterConnectionField | Demonstration plus focused tests |
| 3 | DataLoader for N+1 | N+1 problem with query count; promise library in Python; DataLoader batch_load_fn pattern | Demonstration plus focused tests |
| 4 | Queries, mutations & tests | Query class and resolve methods; Mutation Arguments and InputObjectType; payload errors vs raised GraphQLError | Demonstration plus focused tests |
| 5 | 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 aiodataloader import DataLoader2
3class AuthorLoader(DataLoader):4 async def batch_load_fn(self, keys):5 rows = await sync_to_async(list)(Author.objects.filter(id__in=keys))6 by_id = {row.id: row for row in rows}7 return [by_id.get(key) for key in keys]8
9class PostType(DjangoObjectType):10 author = graphene.Field(AuthorType, required=True)11
12 class Meta:13 model = Post14 fields = ("id", "title", "author")15
16 async def resolve_author(root, info):17 return await info.context.loaders.author.load(root.author_id)Expected result
1Many post.author fields are resolved through one batched author query per request.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from aiodataloader import DataLoader | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 3 | class AuthorLoader(DataLoader): | Creates a class namespace and binds the resulting class object to this name. |
| 4 | async def batch_load_fn(self, keys): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 5 | rows = await sync_to_async(list)(Author.objects.filter(id__in=keys)) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 6 | by_id = {row.id: row for row in rows} | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 7 | return [by_id.get(key) for key in keys] | Returns the observable result to the caller and ends this invocation. |
| 9 | class PostType(DjangoObjectType): | Creates a class namespace and binds the resulting class object to this name. |
| 10 | author = graphene.Field(AuthorType, required=True) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 12 | class Meta: | Creates a class namespace and binds the resulting class object to this name. |
| 13 | model = Post | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 14 | fields = ("id", "title", "author") | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 16 | async def resolve_author(root, info): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 17 | return await info.context.loaders.author.load(root.author_id) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Graphene schema | Automatic model exposure can leak internal fields or create expensive default queries. | Whitelist exposed fields and write explicit mutation validation. |
| Graphene-Django | Automatic model exposure can leak internal fields or create expensive default queries. | Whitelist exposed fields and write explicit mutation validation. |
| DataLoader for N+1 | Blind prefetching can allocate huge object graphs and be slower than targeted queries. | Choose loading based on access pattern and assert query counts on important endpoints. |
| Queries, mutations & tests | Automatic model exposure can leak internal fields or create expensive default queries. | Whitelist exposed fields and write explicit mutation validation. |
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 20 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 | 12 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1def test_private_field_requires_owner(graphql_client, user, other_user, private_post):2 graphql_client.force_login(other_user)3 response = graphql_client.execute(4 "query($id: ID!) { post(id: $id) { id privateNotes } }",5 variables={"id": str(private_post.id)},6 )7 assert response["data"]["post"]["privateNotes"] is None8 assert response["errors"][0]["extensions"]["code"] == "FORBIDDEN"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?