How to Create a Simple Api in PHP and Call Using cURL
This is a straight forward implementation of the API in the PHP. Of course, in a typical production scenario, there would be other requirements, most importantly security and complex business logic requirements that would require DB calls etc..
I am trying to give a basic idea on which you can build your implementation.
// If you want to restrict access calls from a particular domain
header("Access-Control-Allow-Origin: https://myfrontend.com");
$uri = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'POST' && $uri == '/id') {
$name = $_POST['name'];
// implement your logic
// for example: fetch the email address based on
// the value of name received in the request body
// return your response
if (true) {
http_response_code(200);
echo json_encode([
'email' => $email_address,
'msg' => "Success - Address found.",
'color' => "green"
]);
} else {
http_response_code(404);
echo json_encode(['msg' => "Address not found. Please try again.", 'color' => "red"]);
}
} elseif ($method == 'POST' && $uri == '/verify') {
// implement logic for another API
} else {
// implement logic for unknow API calls
http_response_code(404);
echo json_encode(['msg' => "We cannot find what you're looking for."]);
}
This is how you’d call the API from the front-end in vanilla JS
const data = {
name: document.getElementById('first-name').innerText,
}
fetch("https://api.tushargoel.com/id", {
method: "POST",
body: Object.entries(data).map(([k,v])=>{return k+'='+v}).join('&'),
headers: {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"}
})
.then((response) => {
if (response.status === 200) {
return response.json();
} else if (response.status === 404) {
return response.json();
} else {
throw new Error("Something went wrong on API server!");
}
})
.then((response) => {
document.getElementById('api-response').innerText = response.msg;
document.getElementById('api-response').style.color = response.color;
})
.catch((error) => {
console.log(error);
document.getElementById('api-response').innerText = error.error;
document.getElementById('api-response').style.color = error.color;
});
return;
Call API with cURL
function callTGApi() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://tushargoel.com/api/gyan");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
/* Include headers as required */
$headers = array();
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer APIKEY";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
error_log(curl_error($ch));
echo 'Error:' . curl_error($ch);
return "ERROR";
}
curl_close ($ch);
return "SUCCESS";
}