🎓 A1Learner
🔍
0 of 47 lessons completed

API Design Shape

An API is the set of requests that one program offers to other programs. A REST API names the things it serves as nouns, and the request method carries the verb.

A tiny router

A router is the part that matches a request to the code that answers it. This router answers a read and a create.

def show_photo():
    return "photo 42: a beach at sunset"

def create_photo():
    return "new photo saved"

routes = {
    ("GET", "/photos/42"): show_photo,
    ("POST", "/photos"): create_photo,
}
for request in [("GET", "/photos/42"), ("POST", "/photos")]:
    handler = routes[request]
    print(request[0], request[1], "->", handler())

Verb paths next to noun paths

Each verb path needs its own name for one action. The noun shape keeps one path and changes only the method.

pairs = [
    ("/getPhoto/42", "GET /photos/42"),
    ("/createPhoto", "POST /photos"),
    ("/deletePhoto/42", "DELETE /photos/42"),
]
for verb_path, noun_path in pairs:
    print(verb_path, "->", noun_path)

One path, two methods

The path names the same photo in both requests. The method alone changes the action.

actions = {
    ("GET", "/photos/42"): "read photo 42",
    ("DELETE", "/photos/42"): "delete photo 42",
}
for request in [("GET", "/photos/42"), ("DELETE", "/photos/42")]:
    print(request[0], request[1], "->", actions[request])

Example

def list_photos():
    return "all photos"

def show_photo():
    return "photo 42"

def create_photo():
    return "new photo saved"

routes = {
    ("GET", "/photos"): list_photos,
    ("GET", "/photos/42"): show_photo,
    ("POST", "/photos"): create_photo,
}
requests = [("GET", "/photos"), ("GET", "/photos/42"), ("POST", "/photos")]
for request in requests:
    print(request[0], request[1], "->", routes[request]())

Key points

  • API: The set of requests one program offers to other programs.
  • REST API: An API that names resources as nouns and uses the request method as the verb.
  • Resource: A thing the API works with, like a photo or an account.
  • Method: The word on a request, like GET or POST, that says what to do.
  • Noun path: A path like /photos/42 names the resource and nothing else.
  • Verb path: A path like /getPhoto mixes the action into the name, and each action needs a new path.

In this example, the router holds one path per resource and the method picks the action. Reading the list, reading one photo and creating one photo all follow the same noun shape.

Note

A REST API keeps one path per resource, and the method changes the action on that path.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which request follows the REST shape for reading one photo?