Getting a Single Record
The get_one() endpoint retrieves a single country by its primary key. This is the first endpoint where we encounter the concept of resource not found - what happens when the client requests a record that does not exist.
The Model Method
The model method uses $this->db->get_where() to fetch a single record. If no record is found, it returns false. If found, it returns the data as an associative array.
public function get_one(int $update_id): array|false {
$record_obj = $this->db->get_where($update_id, 'countries');
if ($record_obj === false) {
return false;
}
return [
'id' => (int) $record_obj->id,
'country_title' => $record_obj->country_title,
'country_code' => $record_obj->country_code
];
}
Unlike the model from the Basic CRUD chapter, this version does not call die() when the record is not found. Instead, it returns false to the controller, allowing the controller to decide how to respond. This is important for an API - the error response (404) comes from the controller, not the model.
The Controller Method
public function get_one(): void {
$this->authenticate();
$update_id = segment(3, 'int');
if ($update_id === 0) {
http_response_code(400);
echo json_encode(['error' => 'No country ID provided.']);
return;
}
$data = $this->model->get_one($update_id);
if ($data === false) {
http_response_code(404);
echo json_encode(['error' => 'Country not found.']);
return;
}
http_response_code(200);
echo json_encode($data);
$this->log_request('get_one', $update_id);
}There are three response paths in this method:
| Status | When | Response |
|---|---|---|
400 |
No ID provided (segment 3 is 0) | {"error": "No country ID provided."} |
404 |
ID provided but record does not exist | {"error": "Country not found."} |
200 |
Record found | {"id": 1, "country_title": "Afghanistan", ...} |
Notice the distinction between 400 Bad Request and 404 Not Found:
- 400 - The request itself was malformed (missing required ID). This is the client's mistake and should not happen in a well-built client.
- 404 - The request was well-formed but the resource does not exist. This is expected behavior - records may have been deleted between the list and the detail request.
Testing
# Valid request
curl -H "Trongatetoken: your-token" \
http://localhost/countries_api/get_one/1
# Missing ID
curl -H "Trongatetoken: your-token" \
http://localhost/countries_api/get_one
# Non-existent ID
curl -H "Trongatetoken: your-token" \
http://localhost/countries_api/get_one/999URL Segment Behaviour
The segment(3, 'int') call extracts the third segment of the URL and casts it to an integer. If the segment is missing or non-numeric, it returns 0 - which is why we check for === 0. In Trongate, primary keys start at 1, so 0 is a safe sentinel value meaning "no valid ID given."
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.