Reading time: < 1 minutes
Many times, we need to fetch data from a remote server for our applications, and we have to consider creating a small backend to request that data. If you want to send data, I have provided a post where I explain how to generate a POST request with PHP: How to create a POST request using PHP.
I’m going to quickly show you how to create an API using the PHP programming language, which you can deploy on Apache or XAMPP.
- Open your favorite code editor (Notepad++, Visual Studio Code, etc.).
- Create a file and name it obtener_color.php.
- Edit the file and add the following code:
<?php $fruta= $_REQUEST['fruta']; ?>
By adding the line $fruta= $_REQUEST['fruta'];
, we indicate that we are going to receive a GET parameter passed in the URL called “fruta” (fruit in Spanish).
The call to the file from a browser (a browser by default makes a GET request to the requested page) would look like this: http://localhost/obtener_nombre.php?fruta=pera
Now let’s add a small piece of data that will be returned.
<?php $fruta= $_REQUEST['fruta']; if($fruta == "pera"){ echo "verde"; } ?>
With the added code:
if($fruta == "pera"){
echo "verde";
}
We are indicating that if the fruit name is “pera” (pear in Spanish), it should return the color green.
When executed, it will display:
verde
And that’s it for today’s tutorial on quickly creating a small API using PHP.