While working on a PHP site for our Minecraft server, I wanted to create our own API to control the server. In the process, I realized that I needed to learn more about calling a REST API in PHP. The great news is there are many fun public APIs available. This realization was a great chance to create some interesting and dynamic pages. This post will show you the basic steps to implement a REST API in PHP using some interesting examples from NASA, API Ninja, and Youtube.
The Basics
Before we dive into the examples, let’s walk through the basics of how to execute an API request. The examples will use PHP. However, the basic framework works for any language.
What is REST?
An API is an Application Programming Interface. It is a way for two computers to exchange information. The APIs we will be discussing are REST APIs. REST stands for Representational State Transfer. However, it may be simpler to say REST is just an Internet request. If you request a web page, your browser sends a GET request to the web server. The web server sends you the information that you requested. A REST API is the same, just a GET request. With many of the APIs we will discuss, you can put the API request into the address bar of your browser and get a response.
Understand the Basics of the API
The first step in the process is understanding the basics of the API request. Typically we need a URL with an endpoint. The endpoint tells the API what dataset we are seeking. Finding the URL and endpoint is usually fairly easy as most public APIs have reference pages. For example, if you wanted to use the Chess.com API, which provides access to information like player profiles and stats, Chess.com offers a page that describes how to structure the request and the types of information available.
Using the Chess.com API, if you wanted to get the profile information of Magnus Carlsen, currently the top chess player in the world, you can use the following url:
https://api.chess.com/pub/player/magnuscarlsen
Alternatively, you can type this into a command line using cURL:
curl “https://api.chess.com/pub/player/magnuscarlsen”
In our PHP examples below, we will use the PHP version of curl to submit our API requests. In these examples, https://api.chess.com/pub/player/ is the URL and magnuscarlsen is the endpoint.
This example is easy, because it does not have any additional parameters. You only need the URL. However, sometimes you need to add parameters to the request. The parameters tell the API what information you are requesting.
PokéAPI provides access to Pokemon information through an API. If you are looking for information about a specific Pokemon, you can submit the following request:
https://pokeapi.co/api/v2/pokemon/piplup
Instead of requesting data about a specific Pokemon, you can request a list of the first 10 Pokemon with the following request:
https://pokeapi.co/api/v2/pokemon/?limit=10
The last part of the URL, “?limit=10”, is a parameter that provides information to the API about the request. In this case, the number of Pokemon to return. In this case, the parameter can be used with any of the endpoints (e.g., pokemon, abilities, berries). For a more complicated example of parameters, see the Youtube example below.
Parameters are also often used to pass an API key. APIs use an API key to know who is requesting the information and also to set limits on the number of requests to avoid any one person overwhelming the API with requests. For publicly available information, the API key is usually easy to get. You may need to provide name and email address. In the NASA example below, we add the following parameter to the request “?api_key=DEMO_KEY”. DEMO_KEY is the API key.
Making the Request through PHP
Now that we now the basic structure of an API. How do we make the request? We will use curl to make the requests. The general structure is:
- Open the connection.
- Set the options, specifically we want to get the results as a string.
- Execute the request.
- Close the connection.
- Decode the results.
The following example uses the PokeAPI to get a picture of Piplup. To start, we need a connection. In PHP, this is very easy. We only need the following line:
$conn = curl_init();
With the connection open, we next set the options. We will set two options, the URL and also an option to return the results as a string.
curl_setopt($conn, CURLOPT_URL,”https://pokeapi.co/api/v2/pokemon/piplup”);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, true);
After we set the options, we execute the request.
$result = curl_exec($conn);
We close the connection:
curl_close($conn);
Take the results, which are in JSON, and turn them into PHP values.
$pokemon = json_decode($result);
Now we can use the results as we would any other output. When I am learning a new API, I typically use var_dump() or my IDE debugger to look at the output and decide what values from the result I want. In this case, I want the image for Piplup. I can get the image URL from this statement:
$piplup_img = $pokemon->sprites->other->{“official-artwork”}->front_default;
Note that because official-artwork uses a hyphen, you need to enclose in quotes and brackets. Once I have the URL, I can display this on a webpage with:
echo “<img src={$piplup_img} />”
Now that we understand the basic structure, let’s take a look at a few examples.
NASA
One of the first APIs that caught my attention was of course NASA. NASA offers 17 APIs that range from a fun picture of the day to various observational data that can be used by researchers. Access to these APIs is really easy. NASA offers a demo API key (DEMO_KEY) that can be used when exploring the APIs. However, the demo key is limited to 30 requests per hour and 50 requests per day. If you need more requests, sign up for a key is easy with only name and email address. Below is the sample PHP code to show the picture of the day.
echo "<h2>NASA Picture of the Day</h2>";
$url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY";
// Open the connection
$conn = curl_init();
// Set the options
curl_setopt($conn, CURLOPT_URL,$url);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, true);
// Execute
$result = curl_exec($conn);
// Close the connection
curl_close($conn);
// Process and output the results
$pod = json_decode($result);
echo "<img width=\"400\" src={$pod->url}>";
echo "<p>{$pod->explanation}</p>";
This results in the following:
Explanation: You can take a subway ride to visit this observatory in Beijing, China but you won’t find any telescopes there. Starting in the 1400s astronomers erected devices at the Beijing Ancient Observatorysite to enable them to accurately measure and track the positions of naked-eye stars and planets. Some of the large, ornate astronomical instruments are still standing. You can even see stars from the star observation platform today, but now only the very brightest celestial beacons are visible against the city lights. In this time series of exposures from a camera fixed to a tripod to record graceful arcing startrails, the brightest trail is actually the Moon. Its broad arc is seen behind the ancient observatory’s brass armillary sphere. Compare this picture from the Beijing Ancient Observatory taken in September 2023 to one taken in 1895.
API Ninjas
API Ninjas provides a set of 71 APIs that range from fun to practical. The example below requests two random Dad Jokes. API Ninja requires an API key. However, like NASA, it is easy to obtain. API Ninja requires that the API key be placed in the header. Therefore, we will use an additional option CURLOPT_HTTPHEADER. Also in this example, we show how you can place the URL as a parameter in the curl_init function call.
$API_KEY = "X-Api-Key: "YOUR_API_KEY";
$url = "https://api.api-ninjas.com/v1/dadjokes?limit=2";
// Open the connection
$conn = curl_init($url);
// Set options - including adding the API Key to the header
curl_setopt($conn, CURLOPT_RETURNTRANSFER, true);
curl_setopt($conn, CURLOPT_HTTPHEADER, [$API_KEY]);
// Execute
$result = curl_exec($conn);
// Close the connection
curl_close($conn);
// Process the result
// Loop through the jokes and output to the screen.
$jokes = json_decode($result);
foreach($jokes as $currJoke){
echo "<p>{$currJoke->joke}</p>";
}
To the jokes:
Youtube
The Youtube API allows you to retrieve a lot of information about a specific channel (if you have the channel ID). In the example below, we retrieve the latest video id from our Youtube page. We embed the video in a Youtube player and provide the title and description.
$YT_API_KEY = "YOUR_API_KEY";
// Note this url is long with the parameters
$url = "https://www.googleapis.com/youtube/v3/search?channelId=UCXbGlZhpHwwZzNKxRHesl1w&order=date&part=snippet&type=video&maxResults=5&key=". $YT_API_KEY;
$conn = curl_init();
curl_setopt($conn, CURLOPT_URL, $url);
curl_setopt($conn, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($conn);
curl_close($conn);
$videos = json_decode($response);
if (isset($videos->items)){
// Place the first video in an embedded player
echo "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/{$videos->items[0]->id->videoId}\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen></iframe>";
// Add the title and description
echo "<h2>{$videos->items[0]->snippet->title}</h2>";
echo "<p>{$videos->items[0]->snippet->description}</p>";
}
The code results:
Fun Marble Race - Who will Win?
Six colorful marbles race down an amazing marble run track dodging obstacles to the end. Who will win? This simulation was ...
Conclusion
There are many amazing APIs that are waiting to be discovered. This post gave you the basics to be able to implement the APIs using PHP. I am always looking for new APIs. I would love if you add your favorite API to the comments below.