BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
Backend Engineering

Beginner · Lesson 2 of 12

Software Architecture

Design Your First Resource API

Design and test an order API that creates a purchase, retrieves its original receipt and tells a shopper exactly how to fix an invalid quantity.

Two blue notebooks and an order slip beside a wooden index drawer.

A mobile developer has finished the checkout button. The server replies with a green-looking message, “Order received,” and the confirmation screen works. Then someone closes the app, opens it again, and asks to see the receipt. The phone has no order number, no address to fetch and no way to distinguish a saved purchase from a request waiting to be processed. Both teams built their half of checkout. They never agreed on what the successful exchange had to leave behind.

Let's write that agreement for a stationery shop. A customer will buy two blue notebooks and later open the same purchase on another device. By the end you should be able to hand the example to two developers working independently. One can build the server, the other a client, and both can predict what travels over the network on success and what happens when the customer enters zero.

Start with the receipt the customer wants tomorrow

Picture what the orders screen must show after the app has been closed. It needs a stable order identifier, a recorded quantity and price, a currency, and a status. An order is the resource in this design. Its representation is a JSON document describing it at a particular moment. The distinction matters. The same purchase can appear in English or Arabic, and its status might eventually change from received to dispatched. None of those changes should give the purchase a new identity.

Give the collection the path /orders. A customer creates a member by sending POST to that collection. The server allocates a new identifier, say ord_8143, and the resulting member has the path /orders/ord_8143. To retrieve the current representation, send GET to that member. The name of the internal database table, which framework runs the shop, and whether a warehouse gets notified all stay outside this agreement. The client needs to know where to send a message, what to put in it and what it can conclude from the reply.

Customer intent Request Observable success
Place this purchase POST /orders 201, a Location header and an order representation
Open the saved receipt GET /orders/ord_8143 200 and a representation carrying the same ID

Decide who knows each value

For this small shop, one order contains one product and between one and ten units. The signed-in client supplies a product code and an integer quantity. Both fields are required. The server obtains the buyer from the authenticated session, looks up the price and assigns the order ID. It also sets the initial status. Limiting the first contract to one product keeps the exercise small. It is a business decision for this example, not a property of HTTP. A shop with baskets would probably accept an array of lines from the start.

Write a valid request body on a card: {"sku":"N7","quantity":2}. Send it as application/json. The number two is a JSON number. A quoted “2” is a string and this contract rejects it. Decide that unexpected input fields are rejected too. If an older mobile client accidentally sends a field called total, it should receive a useful error instead of thinking the shop agreed to its price. On the response side, give clients the opposite rule: read the documented fields you need and tolerate additional ones. That lets the shop add a delivery estimate later without breaking a receipt screen.

Walk one order through the contract

N7 costs 2,500 fils, or AED 25.00. The signed-in customer requests two units. The server checks the input, finds the product, calculates 5,000 fils and saves the purchase. For this example inventory is sufficient and the operation completes during the request. After the save succeeds, the server returns the following exchange. The quantity and unit price make the arithmetic visible, and the currency removes the ambiguity of an unexplained number on the screen.

HTTP/1.1 201 Created
Location: /orders/ord_8143
Content-Type: application/json

{"id":"ord_8143","sku":"N7","quantity":2,"unitPriceFils":2500,"totalFils":5000,"currency":"AED","status":"received"}

The client reads the Location header as a reference relative to the service origin. It saves the ID alongside the customer’s receipt and shows AED 50.00. A relative reference is useful here because the same example can run against a test host and a production host. The ID is an opaque string to the client. Splitting off the digits and adding one to find the next order would turn a private naming convention into a fragile dependency. Treat the address supplied by the service as the address of this order. HTTP semantics for POST, 201 and Location

The response body saves a round trip when the mobile screen already needs the price and status. Sending an identifier alone would use fewer bytes but force a second read before displaying a complete receipt. Returning the compact representation is worth it for these few fields. That decision might change for an order with thousands of lines or expensive attachments. In either case, say precisely what the creation response contains. Clients should never have to guess whether a field missing on creation means zero, unknown or available only on a later read.

Retrieve the purchase and compare evidence

On another signed-in device, suppose the customer selects order 8143 from their order history. The device sends GET to the member path with no request body. The server checks that the customer can view the order and returns 200 with its current representation. Reading the receipt should not create another purchase. If the customer refreshes three times, a service test should still find exactly one order from the original submission. HTTP permits ordinary operational side effects such as access logging while the requested action remains a read.

Now change today's catalog price to 3,000 fils and repeat that GET. The saved receipt still shows 2,500 fils per unit and 5,000 total. Had the retrieval handler joined to the live price and recalculated the total, the customer would see AED 60.00 for the purchase they just made at AED 50.00. A contract specifies meaning as well as data types. Describing unitPriceFils as the price recorded at purchase time gives a tester a way to detect this bug even though both responses contain valid integers.

Give an unsuccessful client something it can use

Suppose the customer clears the quantity box and the app mistakenly serializes zero. The body is readable JSON, the service understands the content type, and the quantity violates the shop’s range. This contract returns 422 with a problem document. Reserve 400 here for malformed JSON, such as a missing closing brace. Use 415 when the request declares an unsupported media type. A lookup for an unavailable order returns 404 under the shop’s visibility policy. Each distinction changes the action the caller should take.

{"type":"https://shop.example/problems/invalid-order","title":"Check the order details","status":422,"errors":[{"pointer":"/quantity","code":"out_of_range","minimum":1,"maximum":10}]}

Send that body with Content-Type: application/problem+json and an actual HTTP status of 422. The type identifies the kind of problem. The title is readable by a person. The shop defines the errors array and documents the pointer, code and bounds as extensions for this problem type. The client can highlight the quantity control, preserve the selected product and explain the permitted range in the customer’s language. It should branch on the documented code or type rather than matching a sentence that a translator might change. Problem Details for HTTP APIs, RFC 9457

What does an empty result mean? For GET of a particular member, returning 200 and an empty object leaves a client wondering whether the purchase exists but lacks details. The shop returns 404 when the member is absent or hidden from this customer. A signed-in buyer who enters somebody else's order number gets the same public result as a buyer who mistypes a number. The implementation still needs an ownership check on each retrieval. Knowing a resource's address does not establish who may read it.

Capture decisions where a teammate can test them

An OpenAPI description can put the POST operation under /orders and the GET operation under /orders/{orderId}. Declare orderId as a required string path parameter. For creation, describe the required JSON request body, field types, minimum and maximum quantities. For each operation, list responses by status and media type. Include Location in the documented 201 response headers, and use the same reusable order schema for the successful bodies. Give the invalid quantity example alongside the success example so frontend developers can build both views before the server is ready. OpenAPI Specification 3.1.1

Run a small contract test in a fresh fixture. Arrange the price and customer session, submit the two fields, assert the returned status and follow the actual Location. Compare the ID, quantity and total across both responses, then verify the number of purchases. Repeat with zero and assert both the machine-readable error and the absence of a new order. A schema validator can check whether a response has the right shape. It cannot tell whether the service charged today's price for yesterday's purchase. That is why the test sets concrete numbers and checks a business outcome.

One limitation remains. If the connection drops after the database commit, the phone may never receive Location. A blind repeat of POST can produce a second order. This first contract makes no promise about deduplicating submissions. A client should show an uncertain outcome and reconcile with order history or support. A future contract could explicitly support a purchase-attempt key with defined retry behavior. That feature needs agreement about what happens when the same key arrives with different quantities. Simply putting a retry button on a timeout screen makes none of those decisions.

اقرأ الدرس بالعربية

Exercise: write the acceptance test before the handler

A customer buys three N7 notebooks at 2,500 fils each. The catalog price then rises to 2,800. Write down the expected creation status, what destination the client should read next, the amount on that receipt, and the response to a separate submission with quantity eleven. Include one observation that would disprove the implementation even if every JSON document passed schema validation.

Answer. Creation returns 201 and Location identifies the new order. GET of that address by the same customer returns 200 and the original total of 7,500 fils, or AED 75.00. Eleven exceeds the upper bound, so the new submission receives 422 with the quantity error and creates no order. A retrieved total of 8,400 fils, or a second purchase created by refreshing the receipt, is enough to fail the test. Both errors can hide inside perfectly well-formed JSON.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture10 min read

Follow an HTTP Request

Trace a two-notebook purchase from DNS and TLS to a committed order, and learn what a checkout timeout can actually prove.

Read article ↗