$request
variable.
$request = 'https://data.police.uk/api/crimes-street-dates';
We then take the result and use the file_get_contents()
function within PHP which reads the entire response into a string which we will store in the variable $response
.
$response = file_get_contents($request);
Since the API returns information in JSON (JavaScript Object Notation) format, (you can view an example of the raw JSON formatted data here) we need to then format the string to convert it into a PHP array we can manipulate. For that task, we will use the json_decode()
function.
$JSONarray = json_decode($response, true);
We can then print out a list for which months police data are available using the foreach()
construct.
foreach ($JSONarray as $key => $value) {
echo $value["date"] . "<"br">";
}
This service request to the API demonstrates that it contains data from January 2011 to March 2015.
$request = 'https://data.police.uk/api/crime-categories?date=2011-08';
Processing this request in a similar manner as stated above will create a list of the different categories of crimes reported in a given month. As you can see in the request URL, by appending ?date=2011-08
(which is a month/year combination in the form of YYYY-MM) to the query string we can return a list of the crime categories reported in August of 2011. As you can see from the generated list, not all the crime categories are listed. In order to do that, just remove the "date" portion of the query string from the service request.
$request = 'https://data.police.uk/api/crime-categories';
The response from this request can then be used to generate a full list of available crime categories. In all honesty, I expected far more granular data about the crime categories. The Home Office decided that "bicycle theft" was deserving of its own category but yet far more serious crimes like murder/rape/assault are grouped together under the catch-all category "Violence and sexual offences." I find that to be an odd choice because I think there is more public interest in seeing very narrow and specific information of the most serious offenses.
$request = 'https://data.police.uk/api/crime-last-updated';
After the JSON encoded string response has been decoded, the date can be printed using the following:
$first_value = reset($JSONarray);
echo $first_value;
These three service requests provide general information concerning the API. Let's take a look at more specific service requests dealing with police force related data.