← Questions

Write a robust REST API method

0
AppleCodingLast asked Jul 2025

A coding interview question asked in Apple's technical phone screen, last asked Jul 2025. It tests apis, error handling and python.

Implement one REST API method that creates a resource (for example POST /orders). Make it production-quality: a clear request and response schema, validation, correct status codes, safe retries, error handling and tests.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • POST /v1/orders with a JSON body such as {"customer_id": "c_123", "items": [{"sku": "A1", "quantity": 2}]} and an Idempotency-Key header.
  • Success: 201 Created with the new order and a Location header.
  • A retry with the same key and the same body returns the original response, not a second order.

Example

POST /v1/orders  Idempotency-Key: k1  {valid body}         ->  201  {"id": "o_9", ...}
POST /v1/orders  Idempotency-Key: k1  {same body}          ->  201  {"id": "o_9", ...}   # replayed
POST /v1/orders  Idempotency-Key: k1  {different body}     ->  422  idempotency key reused with a different body
POST /v1/orders  {"items": []}                             ->  400  validation error listing the bad fields
POST /v1/orders  (no or bad credentials)                   ->  401

Clarifying questions

  • Who calls it, and how are they authenticated and authorized?
  • How long are idempotency keys kept?
  • Is order creation a single database write, or does it call other services?
  • What rate limits apply?

What a strong answer covers

  • Validation and sanitization at the edge, with error bodies that name each bad field; 400 versus 422 versus 409.
  • Idempotency: store the key, a hash of the body and the response in the same transaction as the order, under a unique constraint, so two concurrent retries can't both create an order.
  • Concurrency: unique constraints and transactions rather than check-then-insert; what a second request sees while the first is still running.
  • Errors and logging: no internal details in responses, structured logs with a request ID, no personal data in logs.
  • Authentication, authorization per customer, rate limiting with 429 and Retry-After.
  • The data model, and unit and integration tests, including a concurrent duplicate test.

Follow-ups

  • Creating the order must also charge a card through another service. What changes?
  • How would you version this API when the schema changes?
  • The idempotency table grows without bound. How do you expire it safely?

Where it's asked

  • Apple · Technical phone screen · Last asked Jul 2025

What it tests

apis · error handling · python

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding