PHP gained fame as easy to learn and at the same time quite powerful programming language.
Throughout its history, it went through several periods of ups and downs, but with the release of the seventh version, PHP confidently returns lost positions and firmly holds the title of one of the most popular languages for web development.
An important part of many web apps is the interaction with external APIs to obtain the necessary data and extend the capabilities of the application. PHP provides a rich set of functions to work with APIs, and we will discuss these functions in more detail in this article.
Browse the Best Free APIs List
Overview of cURL
To work with the APIs, we will use cURL and a free app that allows making HTTP requests in PHP.
The cURL project offers two sub-projects:
- cURL — command-line tool for sending HTTP requests from the terminal. For example,
curl -X GET https://www.google.com/
command sends a GET request to the Google server, and if everything is alright, the server will send the contents of the search page in response. curl is a wrapper for libcurl. - libcurl — transfer library that developers can embed in their programs. It’s very common for PHP to use this library.
Prerequisites to start using API with PHP
To get started we will need PHP itself, so we will install it, as well as the php-curl library.
To do this, type this command in the terminal (we use Ubuntu Linux. If you’re using another OS, the commands may differ):
sudo apt install php php-curl
Request Methods with PHP and cURL
Types of Requests or Request Methods characterize what action we are going to take by calling the API.
There are four main types of actions in total:
- GET: retrieve information (like product information). This is the most common type of request. By using it, we can get the data we are interested in from API.
- POST: adds new data to the server. By using this type of request you can, for example, add a new review of a hotel.
- PUT: changes existing information. For example, by using this type of request, it would be possible to change the text and publication date in an existing blog post.
- DELETE: deletes existing information
What are API Endpoints?
In order to work with APIs through request methods, it is also important to understand the endpoint concept.
Usually, an endpoint refers to a specific address (for example, https://best-tours.com/best-tours-prague). By referring to this address (with certain request method) you get access to certain features/data. In our case – the list of best tours to Prague. Commonly, the name (address) of the endpoint corresponds to the functionality it provides.
Request Method Examples on RapidAPI
To demonstrate the implementation of Request Methods in PHP, we will look at simple API example within the RapidAPI service. This service is an API Hub providing the ability to access thousands of different APIs. Another advantage of RapidAPI is that you can access endpoints and test the work of the API directly in its section within the RapidAPI service.
Let’s try using the KVStore API. This API is used for storage and handling of simple data, such as user form submissions.
How to find APIs on RapidAPI.com
In order to find KVStore API section:
- enter its name in the search box in the RapidAPI service
- or go to “Data” category from “All Categories” list and select this API from the list.
Browse APIsThis API works under freemium conditions, allowing to store a limited amount of data for free, but for our purposes, it will be enough.
Once you select KVStore API, the first page you’ll see is the API Endpoints subsection. This includes most of the information needed to get started. The API Endpoints subsection includes navigation, a list of endpoints, the documentation of the currently selected endpoint, and a code snippet (available in 8 different programming languages) to help you get started with your code.
Once the required API is found, and we can begin to work. We will go through Request Methods (GET POST PUT DELETE) by completing the following steps:
- Make a POST request for the API to create a collection of data.
- Make a GET request where we will use the collection name from the first step, thereby demonstrating GET requests and the fact that the collection was created.
- Make a PUT request where we substitute the modified object and demonstrate the answer.
- Make a DELETE request with the collection name and show the answer.
- Make a GET request with the collection name again to show that the DELETE method worked and there is no collection with such a name.
To get started with this API, we need to call Sign Up endpoint:
1. Make a POST Request
Now we go to the first step and create a collection of data using the Create Collection endpoint. Firstly we need to specify the URL to which we will make a request.
// kvstore API url $url = 'https://kvstore.p.rapidapi.com/collections';
Next, let’s create an object that we will send to the server to create a collection. Here we show that we want to create a collection named RapidAPI:
// Collection object $data = [ 'collection' => 'RapidAPI' ];
Now, we create a new cURL session using the curl_init
method and immediately link it to our URL:
// Initializes a new cURL session $curl = curl_init($url);
Our session needs to be configured. For example, we need to specify the type of request, the request body, the necessary headers, etc.
// 1. Set the CURLOPT_RETURNTRANSFER option to true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 2. Set the CURLOPT_POST option to true for POST request curl_setopt($curl, CURLOPT_POST, true); // 3. Set the request data as JSON using json_encode function curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // 4. Set custom headers for RapidAPI Auth and Content-Type header curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: [Input your RapidAPI Key Here]', 'Content-Type: application/json' ]);
Let’s take a closer look at what we did in the code snippet above. The curl_setopt
method accepts a session handle returned by curl_init
, the parameter we want to configure, and the value for the parameter
- In the first case, we set
CURLOPT_RETURNTRANSFER
parameter to true. It will be necessary for the future, with the help of this setting we will force thecurl_exec
method to return us the answer from the server as a string. - In the second case, we set
CURLOPT_POST
to true and thereby say that we want to make a POST request - In the third case, we add a body to our request, but before that, we need to translate it into the necessary format, so here we make a JSON string from the object
- In the fourth – we write all the necessary headers for the request
After we have prepared our cURL session, we call curl_exec
and pass into it the cURL session descriptor that needs to be executed with all the settings set. And since we previously set the value CURLOPT_RETURNTRANSFER
to true, curl_exec
will return a response from the server, which we will save in the $response
variable.
// Execute cURL request with all previous settings $response = curl_exec($curl);
Next, we need to close the session:
// Close cURL session curl_close($curl);
And also display the response from the server:
echo $response . PHP_EOL;
As a result, we obtain the following file:
<?php // kvstore API url $url = 'https://kvstore.p.rapidapi.com/collections'; // Collection object $data = [ 'collection' => 'RapidAPI' ]; // Initializes a new cURL session $curl = curl_init($url); // Set the CURLOPT_RETURNTRANSFER option to true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the CURLOPT_POST option to true for POST request curl_setopt($curl, CURLOPT_POST, true); // Set the request data as JSON using json_encode function curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Set custom headers for RapidAPI Auth and Content-Type header curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]); // Execute cURL request with all previous settings $response = curl_exec($curl); // Close cURL session curl_close($curl); echo $response . PHP_EOL;
If we run it, we should get this response:
{ "status":"ok" }
It seems that everything is OK!
Note: In order to run files with the above code, you can simply run php <filename>
in the command line.
2. Make the GET Request
Now we will execute a GET request to get data from the server. Most of the parameters will be similar to those specified in the previous step.
According to the documentation in order to get a collection of data, we need to specify its name by adding it to the URL:
$url = 'https://kvstore.p.rapidapi.com/collections'; $collection_name = 'RapidAPI'; $request_url = $url . '/' . $collection_name;
Create a session for url:
$curl = curl_init($request_url);
We also have slightly changed the settings for the session:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]);
As a result, we have the following file:
<?php $url = 'https://kvstore.p.rapidapi.com/collections'; $collection_name = 'RapidAPI'; $request_url = $url . '/' . $collection_name; $curl = curl_init($request_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]); $response = curl_exec($curl); curl_close($curl); echo $response . PHP_EOL;
After its launch, we get the following response with information about the created collection:
{ "items":0, "public_write":false, "email_notification":null, "webhook":null, "webhook_secret":null, "created_at":1564068224.543481, "updated_at":1564068224.543481 }
3. Perform a PUT Request
Perform a PUT request to change data on the server. Suppose we want to set the public_write
field to true. Implementing a PUT request combines the parameters we used to create GET and POST requests, with the difference in just a few parameters.
As a result, we get the following file:
<?php $url = 'https://kvstore.p.rapidapi.com/collections'; $collection_name = 'RapidAPI'; $request_url = $url . '/' . $collection_name; $data = [ 'public_write' => true ]; $curl = curl_init($request_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]); $response = curl_exec($curl); curl_close($curl); echo $response . PHP_EOL;
- At the beginning of the given snippet, we form the URL as in the GET request example.
- Then we create an object in which we change the desired variable. Next, there are the settings almost as in the POST request example, only instead of
CURLOPT_POST
we useCURLOPT_CUSTOMREQUEST
and give it the PUT value because we have a PUT request. - We insert our prepared object in
CURLOPT_POSTFIELDS
in the necessary format, set headers, execute the request, and save results.
After running the created file, we get the response:
{ "status":"ok" }
We can run GET snippet again and check:
{ "items":0, "public_write":true, "email_notification":null, "webhook":null, "webhook_secret":null, "created_at":1564068224.543481, "updated_at":1564079484.550267 }
Success! Data has changed.
4. The DELETE Method
It’s time to delete our collection using DELETE method. Deletion works the same as PUT, only we do not have the request body, and in the CURLOPT_CUSTOMREQUEST
option, we insert the string DELETE. Having all this information, we get the following snippet:
<?php $url = 'https://kvstore.p.rapidapi.com/collections'; $collection_name = 'RapidAPI'; $request_url = $url . '/' . $collection_name; $curl = curl_init($request_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]); $response = curl_exec($curl); curl_close($curl); echo $response . PHP_EOL;
And if we run it, we get the answer:
{ "status":"ok" }
The server responds that the deletion was successful!
5. Repeat GET request and check if the data is really deleted
{ "status":"error", "message":"Collection 'RapidAPI' not found" }
Everything is good. So we went through all the Request Methods.
How to Start Using an API with PHP / cURL
Now we know the basic elements of working with API in PHP, and we can create a step-by-step guide to creating a PHP app with API integration:
1. Get an API key
In order to start working with most APIs, you must identify yourself (register) and get an API key (a unique string of letters and numbers). You will need to add an API key to each request so that the API can recognize you. On the example of RapidAPI – you can choose the method of registration that will be convenient for you. This can be a username, email, and password: Google, Facebook, or Github account.
2. Test API Endpoints with PHP
After receiving the API key, we can make a request to API endpoints (according to the rules in the documentation) to check if everything works as we expected. In the case of working with RapidAPI, immediately after registering with the service, we can go to the section of the API of our interest, subscribe to it and test endpoints directly on the API page. Next, we can quickly create a PHP snippet using the cURL library with requests to the desired endpoint and test its work in the terminal.
3. Make your first PHP app with API
After checking endpoints, we can start creating an application, including the necessary API calls.
Simple PHP API Example
In this example, we will put together everything that we have learned and create our own news search engine using the Web Search API through RapidAPI. This API works under freemium conditions, allowing 10,000 free API requests per month. This will be more than enough for us.
1. Get an API key
After registering with RapidAPI service, we will receive a service key, and this will be enough for us to start work with the Web Search API. You can register by clicking on the ’Sign Up’ button on RapidAPI menu.
As mentioned earlier, you can register in any convenient way:
After registration, click Subscribe to Test button on Web Search API page and you can start using this API.
2. Test the API Endpoints
To create a news search engine we need newsSearch
endpoint. We will specify the necessary parameters according to the documentation and look for the latest news about John Newman.
As we can see, API returns JSON with a selection of news about the singer. It seems that everything works as it should.
3. Make your first app with the API
Now we can start creating our news search engine. This will be an HTML page with a form and a button. The logic of work is simple: you enter a word, press a button, get a list of news about what you entered in the form.
First, let’s make a small HTML template with the form for sending a search request:
<!DOCTYPE html> <html lang="en"> <head> <title>News Searcher</title> </head> <body> <form action="" method="get"> <label for="query">Enter your query string:</label> <input id="query" type="text" name="query" /> <br /> <button type="submit" name="submit">Search</button> </form> <br /> </body> </html>
Now we need to write a php script that will process query field sent in the form and make an API request:
<?php if (isset($_GET['query']) && $_GET['query'] != '') { $url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI'; $query_fields = [ 'autoCorrect' => 'true', 'pageNumber' => 1, 'pageSize' => 10, 'safeSearch' => 'false', 'q' => $_GET['query'] ]; $curl = curl_init($url . '?' . http_build_query($query_fields)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: contextualwebsearch-websearch-v1.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ]); $response = json_decode(curl_exec($curl), true); curl_close($curl); $news = $response['value']; } ?>
Here are some explanations to the snippet above:
_GET
is an object (associative array) that contains variables passed to the script after the form is submitted. First, we check for the presence of query variable in the_GET
array.- After that, we enter the URL to which we will send the request, form an object (array) with the required parameters for the request (inclusively with the value of our query variable).
- Next comes the initialization of the cURL session with needed URL and a string with parameters from the
query_fields
object. - Set the necessary parameters and headers.
- As a result, we execute the session and immediately translate the answer
json_decode
from the string into a PHP array. - We close the session and save the news array to the
$news
variable.
We have received the $news
variable with news, so all we have to do now is just to display them. To do this, we will add the following PHP snippet under our HTML form:
<?php if (!empty($news)) { echo '<b>News by Your query:</b>'; foreach ($news as $post) { echo '<h3>' . $post['title'] . '</h3>'; echo '<a href="' . $post['url'] . '">Source</a>'; echo '<p>Date Published: ' . $post['datePublished'] . '</p>'; echo '<p>' . $post['body'] .'</p>'; echo '<hr>'; } } ?>
This snippet is pretty simple.
In the beginning, we checked if our $news
variable was empty. If $news
is empty, then nothing is displayed, and if there is something in the $news
variable, it will execute the entire code. We then loop through all the news in the array and use echo
to display the required fields from each post.
We combine all our developments into one PHP file:
<?php if (isset($_GET['query']) && $_GET['query'] != '') { $url = 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI'; $query_fields = [ 'autoCorrect' => 'true', 'pageNumber' => 1, 'pageSize' => 10, 'safeSearch' => 'false', 'q' => $_GET['query'] ]; $curl = curl_init($url . '?' . http_build_query($query_fields)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: contextualwebsearch-websearch-v1.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxx' ]); $response = json_decode(curl_exec($curl), true); curl_close($curl); $news = $response['value']; } ?> <!DOCTYPE html> <html lang="en"> <head> <title>News Searcher</title> </head> <body> <form action="" method="get"> <label for="query">Enter your query string:</label> <input id="query" type="text" name="query" /> <br /> <button type="submit" name="submit">Search</button> </form> <br /> <?php if (!empty($news)) { echo '<b>News by Your query:</b>'; foreach ($news as $post) { echo '<h3>' . $post['title'] . '</h3>'; echo '<a href="' . $post['url'] . '">Source</a>'; echo '<p>Date Published: ' . $post['datePublished'] . '</p>'; echo '<p>' . $post['body'] .'</p>'; echo '<hr>'; } } ?> </body> </html>
To run our application, we need to write the code in the index.php file and then open a terminal in the folder with this file and execute the following command:
php -S localhost:5000
This command will start the test server. Our application will be available at https://localhost: 5000. Let’s take a look at it:
Let’s check out its work. Enter a topic on which we want to see the latest news into the form (in our case, this is “Area 51”):
Everything is working! We created our own news search engine. So far it is simple, but nothing will prevent us from gradually expanding its functionality.
Conclusion
In this article, we looked at the features and capabilities of the PHP/cURL bundle for working with API. We studied the implementation of Request Methods using PHP/cURL and even created our own news search service.
PHP is a simple and convenient language for quick web applications development, and by expanding its capabilities using APIs, you can create extremely powerful apps in a very short time.
Related Links
Related Tutorials
- How to use the Cricket Live Scores API (PHP)
- Yahoo Finance API (PHP)
- IMDb API in PHP
- How to use the CoinMarketCap API
Related FAQ
How does an API Work?
API is an interface that allows your application to interact with an external service using a simple set of commands.
Read more at https://rapidapi.com/blog/how-to-use-an-api/
How do you use an API?
- Get an API Key
- Test API Endpoints
- Create your first App
Check out the full guide at https://rapidapi.com/blog/how-to-use-an-api/
What is an API used for?
APIs allow you to save time when developing and help not to invent a bicycle. It is much more efficient and more convenient to use the capabilities of one of the APIs than to try to independently implement similar functionality. Moreover, it will be problematic to get some functions and data other than through the API (for example, a weather forecast, a thematic selection of news, or a high-quality translation from almost any language).
Read more at https://rapidapi.com/blog/how-to-use-an-api/
How to build a REST API using PHP?
Check out all the tutorials on how to create an API with PHP here.
ringtonesdump.com says
Great read. Is it possible to GET with a JOIN in cURL? So you can query based on a shared value between tables? I cant seem to figure out how to do this. A possible new topic: using PHP composer basic set up and test with API. Lots of people struggle there. Thanks again
Dani says
Wonderful article! Thank you sir :))
Phillip Ashmore says
Well I truly liked reading it. This information procured by you is very useful for prper
planning.
Freeman Rudduck says
Genuinely no matter if someone doesn’t understand afterward its up to
other visitors that they will assist, so here it happens.
Ladonna Ruggles says
Thiis info is worth everyone’s attention. How caan I find out more?
RapidAPI Staff says
Hi Ladonna,
Thanks for dropping by. If you need additional support, reach out to support@rapidapi.com.
Thanks!
Lynda Gambrel says
This website was… how do you say it? Relevant!!
Finally I’ve found something which helped me. Thanks!
Daniel says
Thanks for this tutorial!
I need to know how to make a pagination using this php curl.
Example:
endpoint:
https://www.mypage.com?page={5}
https://www.mypage.com?page={6
Thanks a lot!!
Ali says
Get Blank page no response
Ufoeze prince says
Thanks for this. Sir I learnt alot
John says
You saved my life. Too bad I can’t find any ads on this page to express my gratitude!
Imran Patel says
Hello Sir,
Thank you for the great post.
I am working on ZOHO Recruit API.
Can you please explain how can i start with zoho Recruit API there are API key and token and many more to connect with API.
Please suggest.
Looking forward to hear from you
Thank you
dinesh says
hello sir can u please tell me how to upload file using curl
VIshak says
Any github link for the files which are shown in the example ?
Paul says
I’m having an issue with this tutorial. I get an error when I try to run a search: Undefined index: value,
from the $response = [‘value’] variable. How do I rectify this issue? I have everything implemented exactly as in the tutorial above.
myomyo says
Hallo Paul,
I had the same problem.
If you try var_dump($response) you’ll get “Endpoint/api/Search/NewsSearchAPI does not exist”.
Look at https://rapidapi.com/contextualwebsearch/api/web-search , you’ll notice that the right URL is
“https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/search/NewsSearchAPI” (“search” isn’t capitalized)