Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create function to send requests to an API

Tags:

php

api

I have an API that I am trying to create a function for to send requests, the docs are here: http://simportal-api.azurewebsites.net/Help

I thought about creating this function in PHP:

function jola_api_request($url, $vars = array(), $type = 'POST') {
    $username = '***';
    $password = '***';

    $url = 'https://simportal-api.azurewebsites.net/api/v1/'.$url;

    if($type == 'GET') {
        $call_vars = '';
        if(!empty($vars)) {
            foreach($vars as $name => $val) {
                $call_vars.= $name.'='.urlencode($val).'&';
            }
            $url.= '?'.$call_vars;
        }
    }

    $ch = curl_init($url);

    // Specify the username and password using the CURLOPT_USERPWD option.
    curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  

    if($type == 'POST') {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }

    // Tell cURL to return the output as a string instead
    // of dumping it to the browser.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //Execute the cURL request.
    $response = curl_exec($ch);

    // Check for errors.
    if(curl_errno($ch)){
        // If an error occured, throw an Exception.
        //throw new Exception(curl_error($ch));
        $obj = array('success' => false, 'errors' => curl_error($ch));
    } else {
        $response = json_decode($response);
        $obj = array('success' => true, 'response' => $response);
    }

    return $obj;
}

So this determintes whether its a GET or POST request, but the response being returned on some calls is that GET is not supported or POST is not supported, although I am specifying the correct one for each call.

I think I have the function wrong somehow though and wondered if someone could assist me in the right direction? As I've also noticed, I need to allow for DELETE requests too.

like image 590
charlie Avatar asked Dec 07 '22 11:12

charlie


2 Answers

for the easier life, try guzzle. http://docs.guzzlephp.org/en/stable/

you can make a request like this :

use GuzzleHttp\Client;
$client = new Client();
$myAPI = $client->request('GET', 'Your URL goes here');
$myData = json_decode($myAPI->getBody(), true); 

then you can access the data like an array

$myData["Head"][0]
like image 171
Ilham Syahru Ramadhan Avatar answered Dec 09 '22 23:12

Ilham Syahru Ramadhan


The problem is in $url you try to create for GET request.

Your $url for GET request looks like:

GET https://simportal-api.azurewebsites.net/api/v1/?param1=val1&param2=val2

but from documentation you can clearly see that you $url should be:

GET https://simportal-api.azurewebsites.net/api/v1/param1/val1/param2

for ex.:

GET https://simportal-api.azurewebsites.net/api/v1/customers/{id}
like image 27
Dmitry Avatar answered Dec 10 '22 00:12

Dmitry