How to call api in Codeigniter?

by aniya.jaskolski , in category: PHP Frameworks , 9 months ago

How to call api in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 3 months ago

@aniya.jaskolski 

To call an API in Codeigniter, you can use the HTTP client library cURL. Here's an example of how to do it:

  1. First, make sure that the cURL library is loaded:
1
$this->load->library('curl');


  1. Next, set the options for the cURL request. This can include the HTTP method (e.g. GET, POST), the URL of the API, and any data that you need to send with the request:
1
2
3
4
5
6
7
$options = array(
    CURLOPT_URL => 'https://api.example.com/endpoint',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data
);
$this->curl->options($options);


  1. Finally, execute the cURL request and handle the response:
1
2
3
4
5
6
7
8
9
$response = $this->curl->execute();

if ($response === FALSE) {
    // There was an error executing the cURL request
    $error = $this->curl->error_string;
} else {
    // The request was successful
    // Process the response here
}


You can also use the GET, POST, PATCH, DELETE, etc. methods provided by the cURL library as a shortcut for setting the HTTP method and options:

1
2
$this->curl->get('https://api.example.com/endpoint');
$response = $this->curl->execute();