0

So i'm trying to grab data from another url which could be something like:

Random Generated Json

I want to use my Laravel project, as the REST api, for this, meaning that it shouldnt be able to store data, locally, however i should be able to GET/POST something from some API endpoint within my application, however i'm a little bit confused on how to do this.

I've been googleling like i mad man but i can't figure out how to solve my issue.

Can someone point me towards the right direction?

  • Did you get a chance to look into this documentation https://www.itsolutionstuff.com/post/build-restful-api-in-laravel-58-exampleexample.html – Arpit Jain Jan 16 '20 at 13:14

3 Answers3

0

you can use a package like Guzzle.

Then, to consume an api endpoint from within your application, you can simply do something like the following, using the example of random json:

$client = new GuzzleHttp\Client();
$response = $client->get('https://jsonplaceholder.typicode.com/posts/1');
$json = json_decode($response->getBody()->getContents(), true);
adam111
  • 51
  • 2
0

Adam pointed already to Guzzle. You can also use cURL if you don't want to use an external library.

    $headers = [
        'Accept: application/json'
    ];

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);

    $result = curl_exec($ch);

    if ($result === false) {
        throw new \Exception('Curl failed: ' . curl_error($ch));
    }

    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $jsonResult = json_decode($result);

I wrote a little wrapper for my own applications.

Matz
  • 973
  • 8
  • 23
0

The easiest way to do it is by using json_decode(file_get_contents())

See example :

$post = json_decode(file_get_contents('https://jsonplaceholder.typicode.com/posts/1'), true);

And for POST requests you may refer to Pascal MARTIN answer here

Foued MOUSSI
  • 3,911
  • 2
  • 10
  • 30