StaffCoder
Spring Boot
Spring BootSpring Boot 4.1Java 25
12 modules · 48 challengesSign up
Module 2 · REST Controllers & Endpoints

Vending Machine Inventory

easyError HandlingCustom Error Responses100%2 of 2 solved

Problem statement

Add a purchase endpoint to a vending machine API that answers an empty slot with its own status and message.

Requirements

The Slot entity, the ErrorResponse body, the SlotService and the GET /slots endpoint are already provided. Your task is to write the purchase endpoint in SlotController.

SlotService

  • findById(id) returns an Optional holding the slot, or an empty Optional when no slot has that id
  • purchase(slot) takes one item out of the slot, saves it and returns the updated slot

SlotController

POST /slots/{id}/purchase

  • Read the id from the path; the request has no body
  • When the slot has items left, purchase one and return 200 OK with the updated slot
  • When the slot's quantity is 0, return 409 Conflict with an ErrorResponse whose error is "Slot is empty with id: " followed by the id, and leave the slot unchanged
  • Return 404 Not Found when no slot has that id
Sample Requests & Responses

GET /slots

Response (200 OK):

[
  {
    "product": "Trail Mix",
    "quantity": 5,
    "id": 1
  },
  {
    "product": "Cola",
    "quantity": 1,
    "id": 2
  },
  {
    "product": "Chips",
    "quantity": 0,
    "id": 3
  }
]

POST /slots/2/purchase

Response (200 OK):

{
  "product": "Cola",
  "quantity": 0,
  "id": 2
}

POST /slots/2/purchase again

Response (409 Conflict):

{
  "error": "Slot is empty with id: 2"
}

POST /slots/99/purchase

Response (404 Not Found): empty body

More in REST Controllers & Endpoints

See the module
Planetarium Show CatalogThis problem covers adding, listing, and removing shows, and what to answer when someone asks for one that isn't there.50%2 of 4 solvedeasyBird Sightings APIThis problem covers recording bird sightings and finding them by species, and what to show when nothing matches.100%2 of 2 solvedeasyComic Book Issue APIThis problem covers keeping child records inside their own parent, so one series never shows another series' issues.67%2 of 3 solvedeasy

We use cookies that are necessary to run Staffcoder, and optional analytics cookies to see which pages get used. Analytics stays off unless you accept. Read our Cookie Policy.