smartyfy.mrindigi.com

Python Master Course V2 — 093. REST API Design

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 09 — WEB AND API ENGINEERING · LESSON 093 / 200

REST API Design

Estimated study: 80–110 minutes · Prerequisite: preceding lesson, functions, exceptions and structured data.

Course hub

Video lesson

Video not yet available; this area is reserved for a verified video link or player.

Learning outcomes

Model resources and predictable operations. Explain the technical mechanism, interpret outputs, diagnose failures, test edge cases and apply the skill in a realistic system.

Understand and apply: REST API Design

Resource-oriented URLs identify entities; use HTTP methods and status codes consistently, pagination for collections and stable JSON schemas.

Design resources and contracts together

A resource-oriented API gives important domain objects stable identifiers. Products can live at /v1/products/PEN, while the collection lives at /v1/products. The method expresses the operation; avoid inventing a new verb-shaped URL for every implementation function. JSON is a representation of a resource, not the resource’s identity, and using JSON alone does not make an API well designed.

Start with a bounded inventory contract. GET /v1/products lists products; GET /v1/products/{sku} retrieves one; PUT /v1/products/{sku}/quantity sets an absolute quantity; GET /v1/movements lists recorded changes. A stock-issue command can instead use POST /v1/issues with an idempotency key because it represents a new event. Keep these two mutation meanings distinct.

  • Product response: an object with string sku and nonnegative integer qty.
  • Collection response: an object with items plus page, limit and next_page; an empty collection is a successful empty list.
  • Quantity update: an object containing only qty, with authentication and per-resource permission checks.
  • Error response: an object containing error.code and error.message; codes remain stable even if human-readable wording changes.

Python example

import json

def page_products(products, page, limit):
    if type(page) is not int or page < 1:
        raise ValueError("page must be positive")
    if type(limit) is not int or not 1 <= limit <= 100:
        raise ValueError("limit must be between 1 and 100")
    ordered = sorted(products, key=lambda product: product["sku"])
    start = (page - 1) * limit
    items = ordered[start:start + limit]
    next_page = page + 1 if start + limit < len(ordered) else None
    return {"items": items, "page": page, "limit": limit, "next_page": next_page}

products = [{"sku": sku, "qty": 1} for sku in ("PEN", "BAG", "BOOK")]
print(json.dumps(page_products(products, 2, 2), sort_keys=True))

Expected output

{"items": [{"qty": 1, "sku": "PEN"}], "limit": 2, "next_page": null, "page": 2}

Sorting by SKU makes the ordering explicit. Page two skips the first two records and contains PEN. next_page is null because no later record remains. This small in-memory example sorts the whole dataset; a database implementation should use a suitable query and index. Page-number pagination can shift when records are inserted between requests, so mutable large feeds may need cursor pagination or snapshot semantics.

Describe failures before writing routes

Use 404 when a specific product does not exist; return 200 with an empty items list when a valid collection filter finds no products. Choose a documented validation status, such as 400 in this course’s local service, for an invalid quantity. Use 409 for a conflicting idempotency key or another current-state conflict. Do not return internal SQL errors, tokens or tracebacks in public messages.

Versioning gives clients a migration boundary but does not excuse unnecessary breaking changes. Adding a field may be compatible for tolerant clients; renaming sku or changing qty from integer to string is not. Document unknown-field handling, maximum page size, sorting, authentication, rate limits and whether updates require a version or ETag.

For the design project, provide a request and response example for every route plus missing-resource, invalid-data, empty-page and conflict cases. A pure pagination function is not a live HTTP server; it demonstrates the contract that later routing and persistence code must implement. Review that contract with tests before selecting a framework.

Runnable Python example

Requires Python 3.10+. Save as lesson93.py and run using python or python3. The example uses local or in-memory data and makes no external network request.

from urllib.parse import urlencode
print('/products?'+urlencode({'page':2,'limit':10}))

Expected output:

/products?page=2&limit=10

Reasoning walkthrough

Read the imports and setup, identify the data model, then follow each operation until the final result. Change one input and predict the effect before running it. Consider the behavior with empty data, invalid types and missing resources.

Guided real-world project

Design an inventory REST API with versioned routes and error schemas.

  1. Write a specification with data schema, required operations and failure conditions.
  2. Implement a minimal solution using small named functions.
  3. Add input validation and deliberate error responses.
  4. Test typical, boundary and invalid inputs.
  5. Verify the result against an independently calculated expectation.
  6. Document setup, limitations and recovery steps.

Acceptance: deterministic tests, correct handling of rejected data, no undocumented destructive behavior, and a clear explanation of architecture. This project is an assignment; its full implementation has not been independently executed.

Common mistakes and debugging

  • Concatenating untrusted input into SQL or URLs without proper encoding and parameterization.
  • Assuming remote services or databases always succeed.
  • Omitting transaction or timeout boundaries.
  • Confusing transport status with validated application data.
  • Testing only success paths and ignoring empty or malformed responses.

To debug, reproduce the failure, inspect the smallest failing input, check types and constraints, and add a regression test.

Practice with explained answers

Make a prediction before opening each answer. Then trace the example and explain the result in your own words.

Should an empty product search return 404?

Normally no. The collection exists and the valid query found no matches, so return 200 with items: []. A missing individual product is a different case.

Why distinguish set quantity from issue stock?

Setting an absolute quantity and creating a stock issue have different business and retry semantics. A repeated issue can double-decrement without an idempotency contract.

Why include a stable error code as well as a message?

Clients can branch on the code without parsing wording intended for people. The message can improve while the machine-readable contract remains stable.

Why must pagination specify ordering?

Pages are slices of an ordered sequence. Without a stable order, records can appear unpredictably even before considering changes to the dataset.

Does a /v1 prefix prevent breaking clients?

No. It labels a contract. Changing field types or removing fields within that version can still break clients; compatibility requires deliberate schema evolution.

Mastery checkpoint

Reproduce the sample, explain the design, complete the guided project, document three test cases and identify a realistic failure mode. No video, certificate or account-synced completion is claimed.

Course hub · Previous lesson 92 in hub · Next lesson 94 when published.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.