HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 10“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
API Design with REST, OpenAPI and GraphQL Concepts
TechLearningPro's lesson player, the instructor console, and a partner LMS all needed enrollment and progress data in the same week.
Course progress0%
Focus
15 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 10 · Full-Stack Engineering Foundations
Lesson Overview
TechLearningPro's lesson player, the instructor console, and a partner LMS all needed enrollment and progress data in the same week. Each team had guessed a URL shape. One client POSTed to /createEnrollment. Another GETed /api/progress?user=me&all=true and cached the response in a shared CDN entry. A third expected GraphQL because an internal demo had used a single /graphql endpoint for an analytics toy. When the Node service from lesson 9 changed a field name, two clients broke and the third kept showing another cohort's completion rate for twenty minutes. The defect was not Node's event loop. The defect was an undocumented, inconsistent contract with the wrong cache and authorization assumptions.
This lesson designs that contract. REST here means resource-oriented HTTP: nouns for enrollments and progress, methods with known safety and idempotency, and status codes that clients can branch on. OpenAPI is the written description of those resources so humans, generated types, and contract tests agree. GraphQL is a query language and runtime over a typed schema; you will learn its concepts well enough to choose it for a flexible read model and to decline it when a simple progress write needs cacheability, clear authorization, and idempotent retries. The implementation stays on the Fastify service and PostgreSQL parameterized queries from Backend Engineering with Node.js.
The running product is still the TechLearningPro Learning Platform. APIs in this lesson are deterministic product APIs. Model calls can sit behind a resource such as POST /api/lesson-summaries later; the contract must say what is stored, what is generated, and which errors mean "retry" versus "the model refused." That distinction is how full-stack AI stays operable.
Planning assumptions, labeled as design guidance:
The lesson player needs a small, cacheable catalog of public course metadata and an uncacheable, authenticated progress document.
Partner integrations change more slowly than the website. A published OpenAPI document is the compatibility promise.
No API key, signing secret, or learner token appears in examples. Use placeholder header names only.
Status codes and schema fields in examples follow common HTTP and OpenAPI practice. Confirm the current OpenAPI Specification if you generate a document for production.
Learning Objectives
By the end of this lesson you will be able to:
Model TechLearningPro enrollments and lesson progress as HTTP resources with stable URLs.
Choose methods and status codes from safety, idempotency, and what the client must do next.
Write error bodies that machines can branch on without exposing SQL or stack traces.
Describe the API in OpenAPI 3 so a client type and a contract test can be generated from one document.
Version and evolve fields without breaking the partner LMS.
Explain GraphQL schemas, resolvers, and the N+1 query problem at a conceptual level.
Decide when a graph query helps an instructor explorer and when a REST write is the better progress API.
Place authorization on every operation, including object-level checks that a flexible query might skip.
Keep user input in bound SQL parameters on the REST handlers that implement the contract.
Design caching so public metadata may be cached and personalized progress may not.
Specify idempotency for enrollment creation and for any later AI job that charges tokens.
Hand lesson 11 a resource list whose tables, keys, and tenancy filters are obvious.
Prerequisites
Lesson 9's Node service, pool, and rule that identity comes from a verified session. /learn/nodejs is the runtime primer.
Enough SQL to read a SELECT with $1 placeholders. Lesson 11 and /learn/postgresql deepen the schema this API persists.
You can read YAML. OpenAPI examples below are YAML documents, not a second programming language.
If your team already shipped three spellings of "enrollment," start by inventorying them before adding a fourth.
Detailed Core Concepts
Resources, representations, and why URLs are product design
A resource is the thing the client manipulates: an enrollment, a lesson progress record, a course in the catalog. The URL identifies it. The JSON body is a representation, a view you chose to expose, not a dump of the database row. TechLearningPro's enrollment representation includes id, courseSlug, and status. It omits internal surrogate keys you might later rotate, and it omits another learner's identifiers.
REST, in the form this course uses, borrows HTTP semantics rather than requiring a full hypermedia control set. Clients may still hard-code a small set of URLs documented in OpenAPI. What you must not lose is the meaning of methods:
Method
Typical use on this platform
Safe
Idempotent
GET
Read enrollment or progress
Yes
Yes
POST
Create an enrollment or start a summary job
No
No, unless you add an idempotency key
PUT
Replace lesson progress at a known URL
No
Yes
PATCH
Partial progress update
No
Not inherently
DELETE
Withdraw an enrollment
No
Yes
Safe means the method must not change server state. Idempotent means repeating an identical request leaves the resource in the same state as one successful call. POST /api/enrollments without a uniqueness rule creates duplicates when the client retries a timeout. The unique database constraint from lesson 9 makes the operation idempotent in effect; the API should document the already_enrolled result so clients stop treating it as a failure.
Status codes are part of the contract
Use the code to tell the client which branch to run, and a small JSON body to tell it why.
200 with a representation for a successful read.
201 with Location when a create definitely made a new resource.
204 when a delete succeeds and there is nothing to return.
400 when the shape is wrong (not a UUID, unknown field you reject, invalid status).
401 when there is no valid session.
403 when the session is valid and the action is forbidden, and revealing that the resource exists is acceptable.
404 when the resource is absent or when hiding existence is the safer authorization response for learner-scoped ids.
409 when the state conflicts, such as completing a lesson the learner is not enrolled in, or the unique enrollment already exists and you choose to surface conflict rather than a second 201.
422 is used by some teams for semantic validation. Pick one of 400 or 422 for schema versus domain rules and document it. Consistency beats the argument.
429 when rate limited, with Retry-After when you can say so honestly.
503 when the pool or a dependency is unavailable and a later retry might work.
Do not return 200 with { "success": false } for authorization failures. Clients and gateways will cache or count the call as healthy.
Error body, stable and boring:
json
{
"code":"already_enrolled",
"message":"An active enrollment already exists for this course.",
"requestId":"req_01HEXAMPLE"
}
code is the branch key. message is for humans and may be localized later. requestId joins the client report to logs. Omit SQL, table names, and exception classes.
OpenAPI as the source of the contract
The OpenAPI Specification (3.0 or 3.1) describes paths, methods, parameters, request bodies, responses, and reusable schemas. TechLearningPro keeps openapi/learning-platform.yaml in the repo next to the Fastify routes. CI fails if a route's documented status codes drift from the tests. Generated TypeScript types feed the Next.js client so a renamed field fails the build.
OpenAPI does not execute authorization. A schema can say a response is an Enrollment, and a careless handler can still return every row. Contract tests check shapes. Authorization tests check identity. You need both.
Prefer explicit schemas over additional unconstrained objects. additionalProperties: false on write bodies stops mass assignment of role, learnerId, or organizationId. The server sets those from the session.
Versioning and evolution
Breaking changes include removing a field, changing a field's type, or changing the meaning of a status code. Additive changes—new optional response fields, new endpoints—can ship in the current version if clients ignore unknown JSON properties. For a breaking change, publish /api/v2 or a new media type and run both until the partner LMS migrates. Do not version by leaking ?version=2 inconsistently on some routes. Document the sunset date in the OpenAPI description and in the partner changelog.
GraphQL teams sometimes claim they do not need versions because clients name fields. That is only true while you never change a field's meaning, nullability, or authorization. Deprecation directives help. They do not replace a compatibility policy.
GraphQL concepts you must be able to say out loud
A schema defines types and the root fields Query, Mutation, and optionally Subscription. A document from the client selects a tree of fields. A resolver function loads data for one field. Because the client composes the tree, one screen can ask for a learner, their enrollments, and each course title in one round trip. That flexibility is the feature. The costs are real:
Authorization per field or per object. A query that starts at organization { learners { progress } } will over-fetch across tenants if resolvers forget the caller. REST's one handler per action makes the check harder to skip. GraphQL makes it easier to skip unless every resolver receives the caller and enforces it.
N+1 queries. A naive resolver loads enrollments, then runs one SQL statement per enrollment for the course. One instructor page becomes hundreds of database round trips. DataLoader-style batching and a SQL join or WHERE id = ANY($1) are the usual fixes. The concept matters even if you never adopt GraphQL, because a REST endpoint that loops queries has the same shape.
Complexity and caching.GET REST responses for public catalog data can use standard HTTP cache headers. GraphQL typically POSTs to one URL, which intermediaries will not cache as static GETs. Persisted queries and GET with a query hash exist; they are extra machinery. Personalized progress should not be cached at a shared edge in either style.
Unbounded queries. Clients can request deep nesting. Production graph endpoints require depth limits, cost limits, and timeouts. A progress PUT has a naturally small body.
Use GraphQL concepts when the product is an explorer: instructors compose ad-hoc read shapes over data they are already allowed to see. Use REST resources when the product is a command: enroll, set progress, start a billed AI summary. TechLearningPro's player uses REST. An internal instructor explorer can add a graph later without making the player depend on it.
Pagination, filtering, and injection
List endpoints need a bound. Offset pagination (?offset=1000) gets expensive and skips rows if new enrollments insert above the window. Cursor pagination using a stable sort key (created_at, id) is the design this course prefers for enrollments. Filters such as status=active must be validated against an enum and bound as parameters. A filter string that is interpolated into WHERE ${filter} is SQL injection wearing an API.
Sorting: accept sort=created_at and map it through an allow-list to a known column. Never append the query parameter into ORDER BY.
Idempotency keys and future AI operations
POST that charges money, sends mail, or calls a model should accept an Idempotency-Key header the client generates, a UUID it stores for the retry. The server stores the key and the response for a retention window and replays the same response on a duplicate key with the same caller and same body hash. Enrollment creation can rely on the unique (learner_id, course_slug) constraint instead. A lesson-summary job that spends model tokens cannot rely on a unique course slug; the same learner may request a new summary. The key is the deduplication tool. Design the header now so Module 2 does not invent a second mechanism.
Caching and representation headers
Public course catalog GET /api/courses/{slug} may send Cache-Control: public, max-age=60 if the body contains no learner data. Progress GET /api/enrollments/{id}/progress sends Cache-Control: private, no-store. Vary: Authorization matters if any shared cache sits in front. A CDN entry keyed only by URL will serve one learner's progress to the next. That is the bug in the opening story.
ETag on catalog resources supports conditional GETs. Skip ETags on security-sensitive responses until you know caches will not mix them.
Architecture and Design Diagrams
flowchart LR
subgraph clients [Clients]
Player[Lesson player]
Partner[Partner LMS]
Console[Instructor console]
end
subgraph contract [Contract]
OAS[OpenAPI document]
end
subgraph api [Node API]
Routes[REST routes]
Authz[Per-operation authz]
SQL[Parameterized SQL]
end
subgraph optional [Optional read model]
GQL[GraphQL explorer]
end
DB[(PostgreSQL)]
Player --> OAS
Partner --> OAS
OAS --> Routes
Console --> GQL
Routes --> Authz
GQL --> Authz
Authz --> SQL
SQL --> DB
sequenceDiagram
participant P as Partner LMS
participant A as API gateway
participant N as Node route
participant D as PostgreSQL
P->>A: PUT /api/enrollments/{id}/progress
A->>A: authenticate session
A->>N: caller id and body
N->>N: schema validate, reject extra fields
N->>D: UPDATE ... WHERE id = $1 AND learner_id = $2
D-->>N: row count 1
N-->>P: 200 progress representation
Note over P,N: Retry of the same PUT is safe
The graph explorer, if it exists, is a second door to the same authorization and the same database privileges. It is not a shortcut around row filters.
Technical Explanation
Resource design for the learning platform
Resource
URL
Notes
Course catalog item
/api/courses/{slug}
Public read. No learner fields.
Enrollment
/api/enrollments/{enrollmentId}
Authenticated. Scoped to caller.
Enrollment collection
/api/learners/{learnerId}/enrollments
learnerId must equal the session or the caller must be an authorized instructor in that organization.
Future AI command. POST returns 202 and a job URL.
Collection URLs that take a learner id are a common broken-object-level authorization bug. Prefer /api/me/enrollments for the signed-in learner so the client cannot substitute another id. If instructors need a learner-scoped list, use a different operation with an explicit instructor check and an organization predicate, documented separately in OpenAPI.
OpenAPI fragment
This fragment documents the read and the conflict. It is a contract sketch, not a generated file from a live server. Keep it beside the route and update both.
yaml
openapi: 3.0.3
info:
title: TechLearningPro Learning Platform API
version: 1.0.0
paths:
/api/enrollments/{enrollmentId}:
get:
operationId: getEnrollment
parameters:
-$ref:"#/components/parameters/EnrollmentId"
responses:
"200":
description: Enrollment visible to the caller
content:
application/json:
schema:
$ref:"#/components/schemas/Enrollment"
"401":
$ref:"#/components/responses/Unauthenticated"
"404":
$ref:"#/components/responses/NotFound"
components:
parameters:
EnrollmentId:
name: enrollmentId
in: path
required:true
schema:
type: string
format: uuid
schemas:
Enrollment:
type: object
additionalProperties:false
required:[id, courseSlug, status]
properties:
id:
type: string
format: uuid
courseSlug:
type: string
status:
type: string
enum:[active, withdrawn, completed]
Error:
type: object
additionalProperties:false
required:[code, message]
properties:
code:
type: string
message:
type: string
requestId:
type: string
responses:
Unauthenticated:
description: No valid session
content:
application/json:
schema:
$ref:"#/components/schemas/Error"
NotFound:
description: Not found for this caller
content:
application/json:
schema:
$ref:"#/components/schemas/Error"
format: uuid is a documentation hint. The server must still validate. OpenAPI validators differ in how strictly they apply format.
The UPDATE ... FROM enrollments ties the write to the caller's enrollment in one statement. A check-then-update in two round trips races and can be forgotten on one path. additionalProperties: false rejects a body that tries to set learnerId or role. The lesson slug should also be schema-checked against a slug pattern so it cannot carry unexpected Unicode or path tricks into logs; it is still passed as $3, not concatenated.
GraphQL conceptual sketch
graphql
typeQuery{
enrollment(id:ID!):Enrollment
}
typeEnrollment{
id:ID!
courseSlug:String!
progress:[LessonProgress!]!
}
typeLessonProgress{
lessonSlug:String!
percentComplete:Int!
}
A resolver for progress that runs SELECT ... WHERE enrollment_id = $1 per parent is the N+1. A batched resolver collects ids and runs WHERE enrollment_id = ANY($1::uuid[]) with the caller's learner id also bound, then groups rows in memory. Field resolvers still drop objects the caller must not see. This sketch is conceptual. The player does not need this endpoint to ship.
Contract test shape
A contract test loads the OpenAPI document and asserts the route returns only documented status codes and a body that matches the schema. A second test sends role inside the PUT body and expects 400. A third uses two learner fixtures and expects the second to receive 404. A fourth repeats the same PUT and expects the same stored percent, proving idempotency. Run them against a disposable database. They are the evidence that the YAML and the process agree.
Enterprise Real-World Scenarios
Scenario A: Partner timeout duplicate enrollments
The partner LMS retried POST /api/enrollments on a 5-second client timeout. The first insert had committed. Learners saw two active rows and two billing events.
What good looks like. Unique (learner_id, course_slug), documented 409 with already_enrolled, and a partner client that treats that code as success. The OpenAPI document shows the response so the partner does not guess.
Scenario B: CDN-cached progress
GET progress responses omitted Cache-Control. The edge cached the first learner's JSON under the URL.
What good looks like.private, no-store on every personalized response. A test that fails the build if the progress operation's OpenAPI or route header set drifts. Public catalog caching stays on a different path with no Authorization-bearing body.
Scenario C: GraphQL explorer without field authz
An internal tool added organization { learners { email progress } }. Resolvers returned all learners because the first demo used an admin database role.
What good looks like. The explorer uses the same application role as REST, with row predicates. Email is absent from the schema unless a privacy review adds it. Query cost limits are on. The demo admin connection string is not in the server config.
Scenario D: Mass assignment on PATCH
A PATCH forwarded the JSON object into a column update. A client set status to completed on the enrollment and skipped the course.
What good looks like.additionalProperties: false and an allow-list of patch paths. Completing a course is its own operation with its own rules, not a writable column on a generic patch.
Scenario E: Breaking change shipped as "just a field rename"
courseSlug became course_slug overnight. The website deploy was coordinated. The partner LMS was not. Completions stopped posting.
What good looks like. Additive fields first, or /api/v2 with a dated overlap. Generated clients fail CI for the website. The partner changelog and sunset header cover the LMS. Contract tests keep the old operation alive until the date.
Best Practices
Model nouns as resources and put commands that are not CRUD on clear sub-resources such as /summaries.
Document every operation in OpenAPI, including error bodies and idempotency.
Generate client types from that document and check them in CI.
Use HTTP status codes for control flow. Keep { success: false } off the platform.
Make GET safe. Make PUT to a known progress URL idempotent.
Protect POST creates with a unique constraint or an idempotency key, and document which one.
Prefer /api/me/... for learner-scoped collections.
Authorize every operation. Use 404 to hide existence of other learners' ids when that leak matters.
Reject unknown write fields. Never copy a request object into an update.
Validate enums and UUIDs at the edge. Bind every value in SQL.
Allow-list sort fields. Paginate with cursors for growing collections.
Send Cache-Control: private, no-store on personalized representations.
Cache only representations you have proved contain no personal or tenant data.
Return a request id on errors and successes that support staff might see.
Limit list sizes. Default a page size and cap it.
Rate-limit authentication attempts and expensive search or future model routes.
Version breaking changes explicitly. Additive JSON can stay on the current version if clients ignore unknown fields.
If you add GraphQL, enforce caller checks in every resolver, batch SQL, and cap query cost.
Keep the graph explorer off the lesson-player critical path.
Describe future AI operations as jobs with 202, a status URL, and idempotency, so token spend is not a blind POST.
Separate public catalog schemas from authenticated progress schemas in the OpenAPI tags and security requirements.
Review the contract with the partner's timeout and retry behavior, not only with the website's happy path.
Common Mistakes and Anti-Patterns
Verb URLs as the standard (/createEnrollment). Symptom: clients invent more verbs and nobody knows idempotency. Cause: RPC habit. Fix: resources and methods. Keep a single RPC-style path only when you document why REST is a poor fit.
200 for every outcome. Symptom: retries and monitors lie. Cause: a wrapper built for one frontend. Fix: status codes plus code in the body.
Shared cache on personalized GET. Symptom: cross-learner data exposure. Cause: default CDN behavior. Fix: private, no-store and a review of cache keys.
OpenAPI written after launch and never tested. Symptom: the YAML is fiction. Cause: contract treated as documentation only. Fix: contract tests in CI.
Client-supplied learnerId trusted on create. Symptom: enrollment theft or spoofing. Cause: the field was convenient for tests. Fix: session supplies the id; schema rejects the field.
Filter interpolation. Symptom: injection via status or q. Cause: dynamic WHERE builder. Fix: enums, parameters, allow-lists.
Unbounded GraphQL or unbounded includes. Symptom: one request melts the database. Cause: no cost limit, N+1 resolvers. Fix: batching, limits, and a timeout.
GraphQL as a way to skip authorization. Symptom: over-broad reads. Cause: resolvers return whatever the query names. Fix: per-object authz and a non-admin database role.
Breaking renames without a version. Symptom: partner outage. Cause: only the website was in the deploy. Fix: compatibility policy and overlap window.
Pagination with huge offsets. Symptom: slow lists and skipped rows. Cause: OFFSET copied from a small demo. Fix: cursors on a stable order.
Error bodies that include SQL. Symptom: schema leak. Cause: forwarding err.message. Fix: mapped codes only.
AI POST with no idempotency. Symptom: double token spend on retry. Cause: treating generation like a pure function with no side effect. Fix: idempotency key and a job resource.
Troubleshooting and Design Review
Clients retry and create duplicates. Inspect whether the create is documented as idempotent, whether the unique constraint exists, and whether the client treats 409 as success. Capture the partner timeout value; if it is shorter than your p99, retries are guaranteed.
A learner reports seeing the wrong progress. Check Cache-Control, CDN cache keys, and Vary. Then check the SQL predicate. Cache bugs and authorization bugs look similar in screenshots and different in logs.
Contract tests pass and a security test fails. The schema allows the correct shape and the handler still forgets learner_id. Keep authorization tests outside the schema test. Both are required gates.
GraphQL latency grows with the number of enrollments on screen. You have N+1. Log query counts per request in non-production. Batch or replace the field with a REST aggregate that joins once.
Partners still call /api/v1 after sunset. Look at access logs by user agent or client id. Either extend the overlap or block with a 410 and a documented migration. Surprise 404s without a changelog produce support load.
Design review checklist
Is each operation's method idempotent or explicitly not?
Does OpenAPI list success and error responses the tests assert?
Can a client set role, learnerId, or organizationId in a body? If yes, reject the design.
Are personalized responses marked uncacheable?
Are list filters enums or bound parameters?
If GraphQL exists, where is per-object authorization and the query budget?
What is the partner retry behavior for creates and for future summary jobs?
Which fields are safe to add without a version bump?
Knowledge Check
1. What problem does this API contract solve?
It gives the lesson player, the instructor tools, and partner systems one meaning for enrollment and progress: URLs, methods, status codes, errors, cache behavior, and authorization. OpenAPI makes that meaning testable. Without it, each client guesses, retries cause duplicate enrollments, and caches mix learners.
2. When would you choose REST, GraphQL, or both?
Choose REST resources for commands and for cacheable public reads: enroll, replace progress, fetch a course. Choose a GraphQL read model when trusted users need to compose many shapes and you can pay for resolver authorization, batching, and query limits. TechLearningPro can run both against one PostgreSQL authorization model. The player should not depend on the explorer.
3. Which identity and trust boundaries matter?
The client picks the URL and the body; it does not pick the learner identity. The session does. Path ids are untrusted selectors and must be paired with the caller in SQL. A CDN is a shared cache and must not store private representations. A GraphQL query is untrusted input that names data; resolvers enforce access. API documents are public to anyone who ships a client; they are not a secret, and they must not contain sample tokens.
4. What fails in production, and how should the API respond?
Timeouts cause retries: creates conflict with 409 or replay an idempotency key. Invalid bodies get 400 and do not touch the database. Missing sessions get 401. Cross-learner ids get 404. Pool exhaustion gets 503. Validation and authorization failures are not retried blindly; 503 and 429 can be retried with backoff. Model jobs later return 202 and a status resource so the HTTP request is not held open for generation.
5. How do you test the contract, security, and cost?
Contract tests match OpenAPI. Authorization tests use two learners and an instructor. Mass-assignment tests send forbidden fields. Injection tests send SQL punctuation in filters and slugs. Cache tests assert Cache-Control on progress. Load a list endpoint and confirm query count stays flat when page size grows, which catches N+1. For a summary POST, assert a second call with the same idempotency key does not create a second job. Track request rate and, later, tokens per job so a chatty client cannot spend without a limit.
Interview Questions and Answers
Q1. What does idempotent mean for PUT /progress?
Repeating the same request leaves the progress row in the same state as a single success. The client can retry after a timeout without double-counting. POST is not idempotent unless you add a key or a unique constraint and define the replayed response. Interview answers should name the database constraint, not only the HTTP textbook definition.
Q2. Why prefer 404 over 403 for another learner's enrollment id?
403 confirms the id exists. For learner-scoped resources, that confirmation can be an enumeration leak. 404 treats "not yours" and "missing" alike. Use 403 when the caller may know the resource exists and must understand they lack an instructor permission. Document the choice so clients do not special-case the wrong code.
Q3. What is broken object level authorization?
The API checks that the caller is signed in, then uses an id from the path to load or update a row without proving the caller owns it or belongs to its organization. It is a leading API vulnerability class. The fix is a server-side predicate on every query and a test with two identities. Hiding a button is not the fix.
Q4. How does OpenAPI help and what does it not guarantee?
It gives one machine-readable contract for paths, schemas, and status codes, which feeds generated clients and contract tests. It does not authenticate callers, bind SQL parameters, or stop a handler from returning extra rows. A green schema test with a missing learner_id filter is still a security defect.
Q5. How would you evolve courseSlug to a nested course object?
Add the new field while keeping courseSlug. Update clients. Remove the old field in a later version with a sunset period. A same-day rename breaks the partner LMS. GraphQL deprecation follows the same social contract even though the mechanism is a directive.
Q6. Explain N+1 and a fix.
Loading a list and then querying children once per parent multiplies round trips. Batch child loads with WHERE parent_id = ANY($1) or a join, and still bind the caller id. In GraphQL, a batching helper per request is the usual tool. In REST, do not implement the list handler as a loop of queries.
Q7. Why is HTTP caching harder with GraphQL?
Typical GraphQL posts a document to one endpoint, so URL-keyed caches cannot tell public catalog reads from private progress reads. REST lets you put cache headers on each resource. You can design cacheable GraphQL with persisted GET queries, which is additional design. Personalized data stays no-store either way.
Q8. What is mass assignment?
The handler copies client JSON onto a model and persists fields the client should not control: role, owner, price, completion. Mitigation is an explicit allow-list or a schema with additionalProperties: false, plus server-set identity columns. This overlaps with injection only in the sense that both are "untrusted input reached a powerful sink." The sinks differ: columns versus SQL syntax.
Q9. How should a lesson-summary AI call appear on the API?
As a command that creates a job: POST with an idempotency key, 202, and a Location for GET status. The job stores input hashes, caller id, and token counts. The HTTP request does not stream an unbounded provider call on the same timeout as a progress PUT. Authorization is checked when the job is created and again when the result is stored. The response schema separates generated text from authoritative progress.
Q10. Cursor versus offset pagination?
Offset is simple and unstable under inserts, and large offsets force the database to walk skipped rows. A cursor encodes the last seen sort key and id, and the next page uses a parameterized predicate such as (created_at, id) < ($1, $2) together with the caller filter. Clients cannot page into another learner's window if the predicate includes learner_id.
Q11. What would you put in an API design review for a new mobile client?
Resource list, authz model, idempotency of each write, error codes, pagination, cache headers, version policy, rate limits, and how the client should retry 503 versus 400. Ask for the OpenAPI diff and the two-identity test. Decline any design that logs full request bodies by default.
Q12. How do you stop a filter parameter from becoming SQL?
Validate it against an enum or a bounded type. Pass it as a placeholder value. Build ORDER BY and column choices from an allow-list in code. Read the statement in review and confirm the user string appears only in the values array. Add a regression test with a quote and a semicolon.
Hands-On Exercises
Lab note. Extend the lesson 9 service. Do not commit secrets. Use a disposable database. Public sample OpenAPI must not include real tokens.
Exercise 1: Progress contract
Problem. Publish PUT /api/enrollments/{enrollmentId}/progress/{lessonSlug} in OpenAPI and implement it so retries are safe, another learner cannot write, and the response is uncacheable.
Tasks.
Add the path, schemas, and 200/400/401/404 responses to openapi/learning-platform.yaml.
Implement the handler with additionalProperties: false and the parameterized UPDATE that joins the caller's enrollment.
Set Cache-Control: private, no-store.
Tests: owner receives 200; repeat PUT leaves one row; other learner receives 404; body containing role receives 400; a lesson slug containing a quote does not appear in the SQL text.
Optional: a contract test that validates the 200 body against the schema.
Write a short decision note: why this is REST, and which single GraphQL query you would refuse to use for the player.
Cleanup: confirm the OpenAPI file has no bearer tokens and the database is local.
Challenge. Add POST /api/enrollments/{id}/summaries as a stub job that does not call a model. Require Idempotency-Key. The second identical request returns the original job id and does not insert a second row. Document 202 and 401. Describe how you would add a provider timeout later without holding a database transaction during the model call.
Lesson Summary
The learning platform's API is a product surface. REST resources give enrollments and progress methods, status codes, and cache semantics that partners can retry safely. OpenAPI turns that surface into a document CI can enforce. GraphQL remains a powerful read model for an instructor explorer once every resolver carries authorization, batched queries, and a cost limit. None of these styles forgive client-supplied identity, interpolated SQL, or a shared cache on personalized JSON.