PHP: Consuming API with cURL
Tags: php
Published: 2024-03-13 18:40:17

### INTRODUCTION

The Data USA API allows developers to access various data points on demographics, education, employment, housing, and more for locations across the United States. Developers can use this API to integrate data visualizations, perform data analysis, and create applications that leverage this rich source of information.

### EXAMPLE: POPULATION DATA

To get population data at the national level we can use the following API call:

#### Setting up the API URL

```php
$url = 'https://datausa.io/api/data?drilldowns=Nation&measures=Population';
```
starts by defining the URL of the DataUSA API endpoint that provides population data for the entire nation.

#### Setting up the API headers

```php
$headers = [
     // Set the Content-Type header to indicate JSON content.
    'Content-Type: application/json'
];
```
It also sets up an array `$headers` containing the headers needed for the HTTP request. In this case, it sets the `Content-Type` header to `application/json`, indicating that the request will accept and send JSON data.

#### Initializing cURL

```php
$ch = curl_init($url);
```
The `curl_init()` function initializes a cURL session with the specified URL.

#### Setting cURL options

```php
curl_setopt_array($ch, [
    // Set the option to verify the peer's SSL certificate. In this case, 
    // it's set to false to ignore SSL verification.
    CURLOPT_SSL_VERIFYPEER => false,
    // Set the option to return the transfer as a string instead of
    // outputting it directly.
    CURLOPT_RETURNTRANSFER => true,
    // Set a custom request method for the cURL transfer. 
    // In this case, it's a GET request.
    CURLOPT_CUSTOMREQUEST  => 'GET',
    // This option is used to set an array of HTTP headers to include in the request.
    // Each element in the array represents a single header line in the HTTP request.
    CURLOPT_HTTPHEADER => $headers
]);
```
`curl_setopt_array()` is used to set multiple cURL options at once. These options include:

- **`CURLOPT_SSL_VERIFYPEER`**: This option verifies the peer's SSL certificate. In this script, it's set to **`false`** to ignore SSL verification. This might be necessary if the SSL certificate of the server is not valid or if you're testing against a local server.
- **`CURLOPT_RETURNTRANSFER`**: This option specifies that the cURL transfer should return the response data as a string instead of outputting it directly.
- **`CURLOPT_CUSTOMREQUEST`**: This option sets a custom request method for the cURL transfer. Here, it's set to **`'GET'`** to make a GET request.
- **`CURLOPT_HTTPHEADER`**: This option sets an array of HTTP headers to include in the request. In this case, it includes the headers defined earlier.

#### Executing the cURL request and decoding the response

```php
$output = json_decode(curl_exec($ch), true);
```
`curl_exec()` executes the cURL request, and the response is stored in the variable `$output`.

`json_decode()` is used to decode the JSON response into a PHP associative array. The second parameter `true` specifies that the returned objects should be converted into associative arrays.

#### Closing the cURL session

```php
curl_close($ch);
```
`curl_close()` is called to close the cURL session and free up resources.

#### Debug code

```php
var_dump($output);
```
`var_dump()` statement, which can be used for debugging purposes to inspect the structure of the `$output` array.

```php
array (size=2)
  'data' => 
    array (size=9)
      0 => 
        array (size=6)
          'ID Nation' => string '01000US' (length=7)
          'Nation' => string 'United States' (length=13)
          'ID Year' => int 2021
          'Year' => string '2021' (length=4)
          'Population' => int 329725481
          'Slug Nation' => string 'united-states' (length=13)
      1 => 
        array (size=6)
          'ID Nation' => string '01000US' (length=7)
          'Nation' => string 'United States' (length=13)
          'ID Year' => int 2020
          'Year' => string '2020' (length=4)
          'Population' => int 326569308
          'Slug Nation' => string 'united-states' (length=13)
  'source' => 
    array (size=1)
      0 => 
        array (size=4)
          'measures' => 
            array (size=1)
              ...
          'annotations' => 
            array (size=7)
              ...
          'name' => string 'acs_yg_total_population_5' (length=25)
          'substitutions' => 
            array (size=0)
```
The array has two main keys: `'data'` and `'source'`. We'll use the `'data'` key and take the information `'ID Nation'`, `'Population'` and `'Year'`.

#### Outputting the data in an HTML table

```php
echo '<table style="border: 1px solid black;">';
	echo '<thead>';
		echo '<tr>';
			echo '<th>' . 'ID Nation' . '</th>';
			echo '<th>' . 'Population' . '</th>';
			echo '<th>' . 'Year' . '</th>';
		echo '</tr>';
	echo '</thead>';
	echo '<tbody>';
		foreach ($output['data'] as $info) {
			echo '<tr>';
				echo '<td>' . $info['ID Nation'] . '</td>';
				echo '<td>' . $info['Population'] . '</td>';
				echo '<td>' . $info['Year'] . '</td>';
			echo '</tr>';
		}
	echo '</tbody>';
echo '</table>';
```
- The script starts by echoing the opening **`<table>`** tag with some inline CSS for basic styling.
- It then echoes the opening **`<thead>`** tag followed by a row (**`<tr>`**) containing the column headers (**`<th>`**).
- Next, it opens the **`<tbody>`** tag to start the body of the table.
- Inside a **`foreach`** loop, it iterates over each item in the **`$output['data']`** array, which contains the population data.
- For each item, it echoes a new row (**`<tr>`**) containing the population data for a particular nation, with each piece of data enclosed in a table cell (**`<td>`**).
- After looping through all the data, it closes the **`<tbody>`** and **`<table>`** tags.


![table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fyadtsqn704tqx2iw4fn.png)

Overall, this script demonstrates how to use cURL in PHP to fetch data from an API, decode the JSON response, and present the data in an HTML table format.