How to make a request with Curl

Asked

Viewed 9,138 times

3

Hello, folks, I am involved in a project and need to make a request with Curl to get data from an api. But I’ve never used Curl in php that way. Can help me?

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

From what I understand he’s asking for a get with the key to the api, but when I put like this:

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

("11111111111111" equals my key)

He of error 401 saying that my access was denied by invalid credentials. Help me, please. Thank you!

2 answers

7


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

Translation:

  • The -X (uppercase) indicates a custom request, in this case GET, there was no reason for this. Out of curiosity the -x (minusculo) 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 that 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);
  • Well, that helped me a lot, so thank you!

6

I must tell you that the error will remain when using the same beliefs (apparently the beliefs are invalid), to make a Curl with php you can:

$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 by a different means (php) instead of in the shell as you have in the question.

I will leave a functional example (that does not give error 401) 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

  • Thank you, that’s what I wanted! So I can understand.

  • You’re welcome @Krint, I’m glad you solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.