Get Rewarded! We will reward you with up to €50 credit on your account for every tutorial that you write and we publish!

How to send and receive data from a RESTful API using a terminal and PHP

profile picture
Author
Karol Sarbiewski
Published
2024-08-16
Time to read
12 minutes reading time

Introduction

This tutorial explains how to communicate with RESTful API using the cURL library. I will discuss two approaches here:

  • Straight from the server terminal
  • Through PHP

Both approaches will be based on cURL. I will try to tell everything as simply as possible.

Prerequisites

  • Server with cURL installed

    Click here to view commands that install cURL
    • Ubuntu/Debian

      sudo apt install curl
    • CentOS/RHEL

      sudo yum install curl
    • Fedora

      sudo dnf install curl
    • Arch Linux

      sudo pacman -S curl
    • OpenSUSE

      sudo zypper install curl

Example terminology

  • API endpoint: https://api.example.com

Step 1 - Understanding the API

We'll start with a quick introduction. What is an API? It is an "Application Programming Interface" with which we communicate to exchange information. For example:

We have an API which is called "working time". We will send a request to this API to query how long John Doe was at work. In response from the API we will get information about this employee. We will use this example in the rest of the tutorial.

Step 2 - Using cURL

First, we will check if cURL is installed on the system. For this, we will use this command:

curl --version

If we got the version and supported protocols in terminal response, it means that we have cURL on the system. If an error pops up about the lack of cURL support, we need to install it.

If cURL is installed, we can run it. For example, the command to download a file is:

curl -o file-on-your-localhost.html http://example.com/internet-file.html

To find out how long John Doe was at work, we will use this command:

curl \
     -X POST \
     -H 'Authorization: Bearer SUPER-SECRET-TOKEN' \
     -H 'Content-Type: application/json' \
     -d '{"name":"John","lastname":"Doe"}' \
     -i \
     https://api.example.com/post

Let's discuss the purpose of each line:

  • curl

    Since we are "communicating" with the API via HTTP requests, we have to call curl at the beginning.

  • Types of requests -X

    With the -X flag, we define the request method: GET, POST, PUT, DELETE or PATCH. To find out which method does what, we need to go to the documentation of the specific API.

    Note: If no request method is specified, the GET method is automatically selected in cURL. This means, for GET requests, we do not have to add -X GET every time (but we can).

  • Headers -H

    Headers are a “greeting” from the HTTP request. They:

    • Help define the security of the interaction
    • Control the cache
    • Tell you how to interpret the text being sent

    There can be several headers in one request - usually there are more than two. They are added with the -H flag, while the content of the header is in 'apostrophes'.

    In our example, the API requires us to provide a token (security layer; so that the API knows that we are the person we claim to be), so we added the Authorization header. The header Content-Type provides information about what kind of data we will send to the API. In our case it will be text in JSON form.

    If we need to add more headers, we can just add another flag -H.

  • Data -d

    The next element of the command is the data we want to send in the API request. The data is usually in the form of JSON. This is also how it will be in our case. Since we are querying the API for work time, we should provide the first name and last name of the working person. Our JSON looks like this (e.g. data.json):

    {
      "name": "John",
      "lastname": "Doe"
    }

    We can also represent the same JSON data in a single string:

    {"name":"John","lastname":"Doe"}

    To include this data in our query, we need to use the -d flag. We can include this data either directly as a single string or by referencing a file:

    • String:
      -d '{"name":"John","lastname":"Doe"}'
    • File:

      Replace data.json with your file name.

      -d @data.json
  • More information from API

    The final flag is additional, but quite necessary. We are talking here about the -i flag. Thanks to it we will get not only the response from the API but also information about the response headers. Thanks to this, we will know if our response has a code of - for example - 200 (that is, the query executed correctly).

  • API endpoint

    The final element is the address of our API itself. It will be located at the end of the query. There will be no need to write a flag before it — just the address/link itself.

Our entire command for cURL is already written. All we need to do is press the RETURN key and we get the response from the RESTful API.

Step 3 - Understanding the cURL response

Example response from API:

HTTP/2 200
date: Wed, 31 Jul 2024 21:37:00 GMT
content-type: application/json
content-length: 789
server: gunicorn/19.9.0
access-control-allow-origin: *
access-control-allow-credentials: true

{
    "name": "John",
    "last_name": "Doe",
    "hours_working": {
        "monday": "8 hours",
        "tuesday": "5 hours",
        "wednesday": "free",
        "thursday": "10 hours",
        "friday": "7 hours",
        "saturday": "free",
        "sunday": "free"
    }
}

First, we have information about the response headers from the API server. The first line is very important because it tells us that the query was executed successfully — that is, the code 200. HTTP codes can also have other values. Below is a table with the HTTP codes which are assumed to be valid (sometimes the response HTTP code is set individually - then you should read about it in the documentation of the specific API).

HTTP code Meaning of code
100 - 199 Informational responses
200 - 299 Successful responses
300 - 399 Redirection messages
400 - 499 Client error responses
500 - 599 Server error responses

In the next line, we have the date. The next two lines tell us the content of the request and the last three are server or access information. All this information was provided by using the -i flag in the cURL command.

The further part of the response is already the actual content from the API. Here - as we can see - we got the data we asked for. We got information about Mr. John Doe and his working hours. I think we have the basics of sending requests to the API from the command line covered.

Step 4 - Using PHP

Now it's time for PHP. Here, as before, we'll use the cURL library to send requests. As before, we will operate on our imaginary API.

Initializing cURL in code

First, we need to inform PHP that we will want to use cURL. At the very beginning we will have to give it the address to our API server. Also, we'll make a cURL setting right away so that our response is returned as text. Our cURL variable will be named $ch — as it usually is, by default.

$url = 'https://api.example.com/post';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //response in text

Setting the headers

Now we need to set the headers. This will be an array in which any header will be separated by a comma.

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	'Authorization: Bearer SUPER-SECRET-TOKEN',
	'Content-Type: application/json'
));

If we want to add some more headers, we need to add them in the above array. For example:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	'Authorization: Bearer SUPER-SECRET-TOKEN',
	'Content-Type: application/json',
	'Content-style: another header full of information'
));

POST, GET, PUT?

Now we need to tell cURL what type of request we want to send the data. In our case, it will be POST. To the code we add:

curl_setopt($ch, CURLOPT_POST, true);

If we want to make another type of request, such as PUT, PATCH, GET, DELETE, we need to replace the above code with the one below. The code below uses a PUT request. Of course, we can change it to the type we currently need.

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');

Providing the data

Now we need to define the data we want to send to the API. As we remember - it will be a query of how much John Doe worked. We can easily format the data in two ways and pass it to cURL.

Array
The first way is to create a classic array. The data we will use looks as follows:

$data = array(
	"name" => "John",
	"lastname" => "Doe"
);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

JSON string
The second way is to use classic JSON in the form of a string. The code looks like this:

$data = '
{
	"name": "John",
	"lastname": "Doe"
}';

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Sending the query

Now we already have to proceed with the software of sending the entire query to the API. We will add a variable that will store the HTTP code of the request, and we will also add a simple error interpretation of the cURL itself. Finally, we'll close the cURL to free up memory and close the connection.

$response = curl_exec($ch); //sending
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //request code

if(curl_errno($ch)) { //catch errors
	echo 'cURL error: ' . curl_error($ch);
	curl_close($ch);
	exit;
}

curl_close($ch); //closing cURL

Processing the results

Now that the connection has been closed, it remains for us to process the results. The first thing will be to check if we have a valid HTTP code (in our example it will be 200 or 201). You can either echo the JSON result or convert the JSON result into an array to echo it later.

  • Echo entire JSON result

    //checking http code
    if ($http_code == 200 || $http_code == 201) {
        echo $response;
    }
  • Convert JSON result and echo array

    //checking http code
    if ($http_code == 200 || $http_code == 201) {
        $response_data = json_decode($response, true); //json to array
    
        echo "Name: " . $response_data['name'] . "\n"; //echo name
        echo "Last Name: " . $response_data['last_name'] . "\n"; //echo last name
    
        echo "Hours Working:\n"; //show headline
        //loop for echo all the days and hours of work
        foreach ($response_data['hours_working'] as $day => $hours) {
        	echo ucfirst($day) . ": " . $hours . "\n";
        }
    }

To make it easier for us to debug the query in the future, we can add "else" after the condition that checks the HTTP code. This condition will show the response from the server as well as the HTTP code.

if ($http_code == 200 || $http_code == 201) {
	//all the code above
} else {
	echo "HTTP Error: " . $http_code . "\n"; //show HTTP code
	echo "Response: " . $response . "\n"; //show raw response

	$error_data = json_decode($response, true); //decode JSON to array
	print_r($error_data['errors']); //we can print full array with errors - usually the API responds with such a JSON when query id bad/broken
}

Step 5 - Sending the request via PHP

Now that we have the content, we can send the request.

Click here to view the complete PHP file
<?php

// Initializing cURL in code
$url = 'https://api.example.com/post';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //response in text


// Setting the headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
	'Authorization: Bearer SUPER-SECRET-TOKEN',
	'Content-Type: application/json'
));


// POST, GET, PUT?
curl_setopt($ch, CURLOPT_POST, true);


// Providing the data
$data = array(
	"name" => "John",
	"lastname" => "Doe"
);

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));


// Sending the query
$response = curl_exec($ch); //sending
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //request code

if(curl_errno($ch)) { //catch errors
	echo 'cURL error: ' . curl_error($ch);
	curl_close($ch);
	exit;
}

curl_close($ch); //closing CURL


// Processing the results
if ($http_code == 200 || $http_code == 201) {
	echo $response;
} else {
	echo "HTTP Error: " . $http_code . "\n"; //show HTTP code
	echo "Response: " . $response . "\n"; //show raw response

	$error_data = json_decode($response, true); //decode JSON to array
	print_r($error_data['errors']); //we can print full array with errors - usually the API responds with such a JSON when query ID bad/broken
}

In this example, we saved the PHP code in a file called example.php:

Make sure you have the PHP curl extension installed (php-curl).

php example.php

Conclusion

We got it! You just acquired a new skill. You already know how to send a query to the REST API using a terminal and PHP — congratulations :)

License: MIT
Want to contribute?

Get Rewarded: Get up to €50 in credit! Be a part of the community and contribute. Do it for the money. Do it for the bragging rights. And do it to teach others!

Report Issue
Try Hetzner Cloud

Get €20/$20 free credit!

Valid until: 31 December 2025 Valid for: 3 months and only for new customers
Get started
Want to contribute?

Get Rewarded: Get up to €50 credit on your account for every tutorial you write and we publish!

Find out more