Programing

Laravel에서 외부 API로 HTTP 요청 수행

lottogame 2020. 6. 26. 08:10
반응형

Laravel에서 외부 API로 HTTP 요청 수행


내가 원하는 것은 HTTP (예 : jQuery의 AJAX) 요청이있는 API에서 외부 API로 객체를 얻는 것입니다. 어떻게 시작합니까? Google 씨에 대해 조사했지만 도움이되는 내용을 찾을 수 없습니다.

궁금해지기 시작한이조차도 가능합니까? 이 게시물에서 Laravel 4는 컨트롤러에서 외부 URL로 게시 요청을 수행하여 가능한 것처럼 보입니다. 그러나 문서를 찾을 수있는 예나 출처는 없습니다.

도와주세요?


https://stackoverflow.com/a/22695523/1412268 에서 비슷한 질문에 대한 답변을 기반으로합니다.

Guzzle보십시오

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' =>  ['user', 'pass']]);
echo $res->getStatusCode(); // 200
echo $res->getBody(); // { "type": "User", ....

우리는 Laravel에서 패키지 Guzzle을 사용할 수 있습니다. HTTP 요청을 보내는 PHP HTTP 클라이언트입니다.

작곡가를 통해 Guzzle을 설치할 수 있습니다

composer require guzzlehttp/guzzle:~6.0

또는 프로젝트의 기존 composer.json에서 Guzzle을 종속성으로 지정할 수 있습니다.

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}

아래와 같이 Guzzle을 사용하는 laravel 5의 예제 코드,

use GuzzleHttp\Client;
class yourController extends Controller {

    public function saveApiData()
    {
        $client = new Client();
        $res = $client->request('POST', 'https://url_to_the_api', [
            'form_params' => [
                'client_id' => 'test_id',
                'secret' => 'test_secret',
            ]
        ]);
        echo $res->getStatusCode();
        // 200
        echo $res->getHeader('content-type');
        // 'application/json; charset=utf8'
        echo $res->getBody();
        // {"type":"User"...'
}

외부 URL을 호출하고 결과를 사용하고 싶습니까? JSON을 제공하는 무언가에 대한 간단한 GET 요청에 대해 이야기하는 경우 PHP는 즉시 이것을 수행합니다.

$json = json_decode(file_get_contents('http://host.com/api/stuff/1'), true);

게시 요청을하고 싶다면 조금 어렵지만 curl을 사용하여이를 수행하는 방법에 대한 예제가 많이 있습니다.

그래서 나는 그 질문이 있다고 생각합니다. 정확히 무엇을 원하세요?


2019 년 3 월 21 일에 업데이트 됨

GuzzleHttp사용하여 패키지 추가composer require guzzlehttp/guzzle:~6.3.3

또는 Guzzle을 프로젝트의 종속성으로 지정할 수 있습니다 composer.json

{
   "require": {
      "guzzlehttp/guzzle": "~6.3.3"
   }
}

API를 호출하는 클래스의 맨 아래에 아래 행을 포함하십시오.

use GuzzleHttp\Client;

요청을 위해 아래 코드를 추가하십시오

$client = new Client();

    $res = $client->request('POST', 'http://www.exmple.com/mydetails', [
        'form_params' => [
            'name' => 'george',
        ]
    ]);

    if ($res->getStatusCode() == 200) { // 200 OK
        $response_data = $res->getBody()->getContents();
    }

Httpful을 사용할 수 있습니다 :

웹 사이트 : http://phphttpclient.com/

Github : https://github.com/nategood/httpful


Definitively, for any PHP project, you may want to use GuzzleHTTP for sending requests. Guzzle has very nice documentation you can check here. I just want to say that, you probably want to centralize the usage of the Client class of Guzzle in any component of your Laravel project (for example a trait) instead of being creating Client instances on several controllers and components of Laravel (as many articles and replies suggest).

I created a trait you can try to use, which allows you to send requests from any component of your Laravel project, just using it and calling to makeRequest.

namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
    /**
     * Send a request to any service
     * @return string
     */
    public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
    {
        $client = new Client([
            'base_uri' => $this->baseUri,
        ]);

        $bodyType = 'form_params';

        if ($hasFile) {
            $bodyType = 'multipart';
            $multipart = [];

            foreach ($formParams as $name => $contents) {
                $multipart[] = [
                    'name' => $name,
                    'contents' => $contents
                ];
            }
        }

        $response = $client->request($method, $requestUrl, [
            'query' => $queryParams,
            $bodyType => $hasFile ? $multipart : $formParams,
            'headers' => $headers,
        ]);

        $response = $response->getBody()->getContents();

        return $response;
    }
}

Notice this trait can even handle files sending.

If you want more details about this trait and some other stuff to integrate this trait to Laravel, check this article. Additionally, if interested in this topic or need major assistance, you can take my course which guides you in the whole process.

I hope it helps all of you.

Best wishes :)

참고URL : https://stackoverflow.com/questions/22355828/doing-http-requests-from-laravel-to-an-external-api

반응형