How to make a request with curl

3

Hello everyone, I'm involved in a project and I need to make a request with curl to get data from an api. But I've never used curl in php that way. Can you help me?

curl -X GET https://jsonodds.com/api/odds/nfl -H "JsonOdds-API-Key: yourapikey"

By what I understand he is asking for a get with the api key, but when I put it like this:

'https://jsonodds.com/api/odds?JsonOdds-API-Key=11111111111111

("11111111111111" is equivalent to my key)

It from error 401 saying that my access was denied by invalid credentials. Help me please. Thanks!

    
asked by anonymous 14.03.2017 / 17:49

2 answers

6
curl -X GET https://jsonodds.com/api/odds/nfl -H "JsonOdds-API-Key: yourapikey"

Translation:

  • The -X (upper case) indicates a custom request, in this case GET , nor was there a reason for this. Out of curiosity -x (small) indicates a proxy (logo -x usr:[email protected]:80 ) .

  • The -H is a HEADER , a header, in this case with the value of JsonOdds-API-Key: yourapikey .

  • The https://jsonodds.com/api/odds/nfl is the same link, which will connect. : P

Now to do this in PHP, in the same order:

// Iniciamos a função do CURL:
$ch = curl_init('https://jsonodds.com/api/odds/nfl');

curl_setopt_array($ch, [

    // Equivalente ao -X:
    CURLOPT_CUSTOMREQUEST => 'GET',

    // Equivalente ao -H:
    CURLOPT_HTTPHEADER => [
        'JsonOdds-API-Key: yourapikey'
    ],

    // Permite obter o resultado
    CURLOPT_RETURNTRANSFER => 1,
]);

$resposta = json_decode(curl_exec($ch), true);
curl_close($ch);
    
14.03.2017 / 18:22
6

I have to say that the error will remain when you use the same credentials (apparently the credentials are invalid), to make a curl with php podes:

$url = 'https://jsonodds.com/api/odds?JsonOdds-API-Key=';
$apiKey = '11111111111111';
$curl = curl_init($url.$apiKey);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
$return = curl_exec($curl);
curl_close($curl);

echo $return; // a tua resposta em string json
$arrResp = json_decode($return, true); // o teu json de resposta convertido para array

Note that you are using exactly the same tool but in a deferential way (php) instead of being in the shell as you have in the question.

I'll leave a working example (not giving 401 error) below:

$url = 'https://raw.githubusercontent.com/Miguel-Frazao/us-data/master/zip_codes_us.json';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
$return = curl_exec($curl);
curl_close($curl);

echo $return; // a tua resposta em string json
$arrResp = json_decode($return, true); // o teu array criado a partir do json de resposta
    
14.03.2017 / 18:00