In this article I will walk you on how I refactor my api request from curl to Codeigniter 4 curlrequest, which in turns gives a more maintainable codes.
What is Curlrequest in Codeigniter
The CURLRequest class is a lightweight HTTP client based on CURL that allows you to talk to other web sites and servers. It can be used to get the contents of a Google search, retrieve a web page or image, or communicate with an API, among many other things.
Without much ado let look at the curl library I was using before refactoring.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 200);
curl_setopt($ch, CURLOPT_TIMEOUT, 200);
$headers = array('Content-Type: application/json', 'Authorization:' . $token);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$request = curl_exec($ch);
$result = json_decode($request, true);
return $result;
Converting this to the curlrequest class, the first thing is to load the class.
$client = \Config\Services::curlrequest();
$response = $client->request('POST', 'api.example.com', [
'json' => $postData,
'headers' => [
'content-type' => 'application/json',
'cache-control' => 'no-cache',
'Authorization' => "Bearer xxxxxxxx",
],
]);
Explanation
On the first line we load the class
the $client->request() accept three arguments, first is the request method which in this case is POST, the url and the third is array where we pass our data.
To read more on visit Codeigniter 4 documentation
Conclusion
It is obvious that the codeigniter 4 curlrequest class is more concise and readable compare to the traditional CURL Library.
If there is any difficulty, of course you can comment.
Top comments (1)
Hy, i was hoping you can help me on the current project i am on, i have been trying to write an affiliate code for code igniter 4, affiliate to register under affiliate. once a user is registered a referral link is generated and then other user can use the link to generate there own and register as an affiliate under the first person, can you help with some code to execute this, thanks