How to call an API in PHP (Beginner-guide)

What is API?

API is stands for Application Programming Interface, It is like a middleware that helps two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you're using an API.

Today we will learn how we can call an API and how we can display the API response with examples. 


API

We have 2 options: first one is CURL method and second one is normal PHP functions.

1.) Call an API using CURL: cURL is a tool for transferring files and data with URL syntax, supporting many protocols including HTTP, FTP, TELNET and more. Initially, cURL was designed to be a command line tool. Lucky for us, the cURL library is also supported by PHP.

How to use it:

create curl resource 

$ch = curl_init();

- set url 

curl_setopt($ch, CURLOPT_URL, "http://example.com");   

- $output contains the output json 

$output = curl_exec($ch); 

- close curl resource to free up system resources 

curl_close($ch);   


Example: 

<?php  

$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL, "https://api.genderize.io/?name=Anil"); 

$output = curl_exec($ch); 

curl_close($ch); 

var_dump(json_decode($output, true)); 

?>

Output:

{"name":"Anil","gender":"male","probability":0.97,"count":6560}

In this above example we call this URL (https://api.genderize.io/?name=Anil) and after calling this it return us results. So using API calling we access the other website data and display it on our website.


2.) Call an API using PHP functions: Using file_get_contents() function we can call an API. It's easy to use and its single line code.

Syntax: $data = file_get_contents ($my_url);

This will return the raw data stream from the URL.


Example:

<?php

$url = "https://api.genderize.io/?name=Anil";

$getcontent = file_get_contents($url);

$output = json_decode($getcontent, true);

print_r($output); // return result in array

echo "<br>".$output['name']; // display only name

?>

Output:

Array ( [name] => Anil [gender] => male [probability] => 0.97 [count] => 6560 )

Anil 

In this above example we get the data from "api.genderize.io" website. It return data in json format so we convert it into array using json_decode() function.

That's it! Please try it yourself and let us know if you face any issue or error. You can comment your questions or suggestions through below comment box. 

Thanks!

Also Check these following interesting posts:

5 Best free online QR Code Generator Websites in 2020

Free online tools that you must want to try  

Top 20 Most-subscribed YouTube channels worldwide 2020




Post a Comment

0 Comments