Nowadays, the common response from an API is JavaScript Object Notation (JSON) or eXtensible Markup Language (XML).
In this tutorial, we going to use JSON, because it's simplicity and clean structure.
API Responses not limit to JSON / XML only, it can be images, videos, etc.
Now, create a file named response.php
and add the following codes
<?php
require_once 'funcs.php';
// response('some data');
// response(['some' => 'data']);
// response(true);
response([1, 2, 3, 4]);
// response('ops! something went wrong!', true, 400);
function response($value, $error = false, $code = 200)
{
// return output as json, instead of text/html
header('Content-Type: application/json');
// set http status code
http_response_code($code);
// handle error output
if ($error) {
// convert to JSON format and echo
echo json_encode([
'error' => true,
'message' => $value,
'status' => $code,
]);
return;
}
// normal output, with standard format
$output = [
'data' => $value,
];
// convert to JSON format and echo
echo json_encode($output);
}
Now open up your browser or in Postman and enter http://localhost:8000/response.php
.
You can comment and uncomment sample codes from line 16 to 20 to see different results.