Skip to Content
Course content

236: Building an Inventory Management API

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're running a massive physical warehouse. You’ve got thousands of boxes, and you can't possibly let every single salesperson walk into the aisles and start counting things themselves—they'd trip over each other and probably lose half the stock. Instead, you hire a warehouse foreman. The foreman stands at a window. If a salesperson wants to know how many blue widgets are left, they hand the foreman a note. The foreman goes into the back, checks the shelf, and comes back with a written answer. If they want to add more stock, they hand over a delivery manifest, and the foreman updates the records.

In this lesson, your PHP code is that foreman. The "note" is the HTTP request, the "warehouse" is your database, and the "written answer" is the JSON response. You aren't building a website with buttons and colors; you're building a communication interface that other software can talk to.

Routing the Warehouse Requests

First, we need to figure out what the "note" is asking for. In a RESTful API, we use HTTP methods to define the action. I always tell my juniors to think of it as a verb. GET is "tell me," POST is "create this," PUT is "update this," and DELETE is "get rid of this."

// A simplified routing logic for our inventory
$method = $_SERVER['REQUEST_METHOD'];
$resource = $_GET['action'] ?? '';

switch ("$method:$resource") {
    case 'GET:products':
        handleGetProducts();
        break;
    case 'POST:products':
        handleCreateProduct();
        break;
    case 'PUT:stock':
        handleUpdateStock();
        break;
    default:
        http_response_code(404);
        echo json_encode(["error" => "Foreman doesn't know what that is."]);
        break;
}

Validating the Manifest

Now, the foreman can't just trust every note he gets. If a salesperson hands him a note saying, "Add -500 widgets to the shelf," that's a problem. In PHP, when you're dealing with php://input (which is where the JSON body lives), you have to be ruthless about validation.

I've seen too many APIs crash because someone passed a string where an integer was expected. You need to decode the JSON and verify that the data is actually usable before it ever touches your database.

function handleUpdateStock() {
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['product_id']) || !isset($input['quantity'])) {
        http_response_code(400);
        echo json_encode(["error" => "Missing product ID or quantity."]);
        return;
    }

    if (!is_int($input['quantity'])) {
        http_response_code(400);
        echo json_encode(["error" => "Quantity must be a whole number."]);
        return;
    }
    
    // Now we can safely proceed to the database update...
}

Keeping the Count Honest

The core of inventory management isn't just adding or subtracting; it's ensuring you don't sell things you don't have. This is where your business logic lives. You shouldn't just run an UPDATE query blindly. You need to check the current stock level first, or better yet, use a SQL query that prevents the stock from dipping below zero.

Using a WHERE quantity >= :decrement clause in your update is a pro move. It prevents "race conditions" where two different API calls try to sell the last item at the exact same millisecond.

// Example of a safe stock deduction
$stmt = $pdo->prepare("UPDATE products SET quantity = quantity - :qty WHERE id = :id AND quantity >= :qty");
$stmt->execute(['qty' => $decrement, 'id' => $productId]);

if ($stmt->rowCount() === 0) {
    http_response_code(409); // Conflict
    echo json_encode(["error" => "Insufficient stock for this operation."]);
} else {
    echo json_encode(["status" => "Stock updated successfully."]);
}

Talking Back in JSON

The most common mistake I see is PHP leaking a warning or an error message into the output, which breaks the JSON format and makes the client-side app crash. Your API should speak one language and one language only: JSON.

Always set your header at the very top of your script. This tells the receiving app, "Hey, don't treat this as a webpage; treat it as data."

header('Content-Type: application/json; charset=utf-8');
// Now everything you echo will be interpreted as JSON



📋 Practical Task

Build a "Low-Stock Alert" Endpoint

Your inventory API is working, but the warehouse manager is tired of checking every item manually. Your task is to create a new endpoint: GET /products/low-stock.

Requirements:

  • The endpoint must accept an optional query parameter called threshold (e.g., ?threshold=10).
  • If no threshold is provided, default the value to 5.
  • The API should query the database and return a JSON array of all products where the current quantity is less than or equal to that threshold.
  • Each product in the array should include the product_name, sku, and current_quantity.
  • Ensure you set the correct Content-Type header and handle cases where no low-stock items are found (return an empty array, not an error).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.