itsource

PHP에서 REST API 호출

mycopycode 2022. 9. 28. 00:09
반응형

PHP에서 REST API 호출

고객이 PHP 호출에 필요한 REST API를 제공했습니다.그러나 사실 API에 기재되어 있는 문서는 매우 한정되어 있기 때문에 서비스를 어떻게 호출해야 할지 잘 모르겠습니다.

구글에 접속해 봤지만 이미 만료된 야후! 서비스 호출 방법 튜토리얼만 떴다.머리글이나 상세한 정보는 언급하지 않았습니다.

REST API를 호출하는 방법이나 그에 대한 문서와 관련된 괜찮은 정보가 있습니까?왜냐하면 W3 학교에서도 SOAP 방식만 설명되기 때문입니다.나머지 API를 PHP로 만들기 위한 다른 옵션은 무엇입니까?

PHP의 에는 PHP의 REST API로 할 수 .cURL API 파라미터 등)은 클라이언트에 의해 제공되어야 .

예제:

// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value

function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, "username:password");

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

URL이 있고 php가 지원하는 경우 file_get_contents를 호출하면 됩니다.

$response = file_get_contents('http://example.com/path/to/api/call?param1=5');

$response가 JSON인 경우 json_decode를 사용하여 php 배열로 변환합니다.

$response = json_decode($response);

$response가 XML인 경우 simple_xml 클래스를 사용합니다.

$response = new SimpleXMLElement($response);

http://sg2.php.net/manual/en/simplexml.examples-basic.php

Guzzle을 사용하세요.「HTP/1.1 의 조작을 용이하게 해, Web 서비스를 소비하는 수고를 덜어주는 PHP HTTP 클라이언트」입니다.guzzle을 사용하는 것이 cURL을 사용하는 것보다 훨씬 쉽습니다.

다음은 웹 사이트의 예입니다.

$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', [
    'auth' =>  ['user', 'pass']
]);
echo $res->getStatusCode();           // 200
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody();                 // {"type":"User"...'
var_export($res->json());             // Outputs the JSON decoded data

CURL은 가장 간단한 방법입니다.간단한 전화입니다.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "THE URL TO THE SERVICE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, POST DATA);
$result = curl_exec($ch);


print_r($result);
curl_close($ch);

HTTPFUL 사용

Httpful은 심플하고 체인 가능하며 읽기 쉬운 PHP 라이브러리입니다.개발자는 curl set_opt 페이지를 거치지 않고 API와의 상호작용에 집중할 수 있으며 이상적인 PHP REST 클라이언트입니다.

httpful에는 다음이 포함됩니다.

  • 판독 가능한 HTTP 메서드 지원(GET, PUT, POST, DELETE, HEAD 및 OPTIONS)
  • 커스텀 헤더
  • 자동 "스마트" 구문 분석
  • 자동 페이로드 시리얼라이제이션
  • 기본 인증
  • 클라이언트측 증명서 인증
  • "템플릿" 요청

예.

GET 요청을 전송합니다.자동으로 구문 분석된 JSON 응답을 가져옵니다.

라이브러리는 응답에서 JSON Content-Type을 인식하고 응답을 네이티브 PHP 개체로 자동 구문 분석합니다.

$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)->send();

echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";

API를 쉽게 만들 수 있는 어플리케이션인 POSTMAN을 선택하실 수 있습니다.요청 필드를 입력하면 다른 언어로 코드가 생성됩니다.오른쪽 코드를 클릭하여 원하는 언어를 선택합니다.

가 "REST API"를 지원하는지 .GET ★★★★★★★★★★★★★★★★★」POST을 사용하다아래 코드는 저에게 맞는 것입니다.저는 제 웹 서비스 API를 호출하고 있기 때문에 API가 무엇을 사용하고 무엇을 반환하는지 이미 알고 있습니다. 가지 을 모두 지원합니다.GET ★★★★★★★★★★★★★★★★★」POSTmethods를에 덜 는 "중요한 정보"에 .URL (GET), 는 「사용자명」, 「패스워드」로 POST이 잘 안 풀린다.HTTPS★★★★★★ 。

코드 형식으로 명령어 API를 사용하면 .echo $my_json_variable클라이언트가 json 문자열을 사용할 수 있도록 합니다.

보시다시피 제 API는 json 데이터를 반환하지만 API로부터의 응답이 어떤 형식으로 되어 있는지 알아야 합니다(또는 반환된 데이터를 보면 알 수 있습니다).

클라이언트 측에서 API에 접속하는 방법은 다음과 같습니다.

$processed = FALSE;
$ERROR_MESSAGE = '';

// ************* Call API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myapi.com/api.php?format=json&action=subscribe&email=" . $email_to_subscribe);
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=myname&password=mypass");   // post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close ($ch);

// returned json string will look like this: {"code":1,"data":"OK"}
// "code" may contain an error code and "data" may contain error string instead of "OK"
$obj = json_decode($json);

if ($obj->{'code'} == '1')
{
  $processed = TRUE;
}else{
  $ERROR_MESSAGE = $obj->{'data'};
}

...

if (!$processed && $ERROR_MESSAGE != '') {
    echo $ERROR_MESSAGE;
}

도 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.file_get_contents()여기 사용자들 중 몇 명이 제안한 방법이지만, 그 소음은 제게는 잘 맞지 않습니다.는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★curl보다 빠르고 신뢰할 수 있는 방법을 제공합니다.

@Christoph Winkler가 언급한 바와 같이 이것은 이를 달성하기 위한 기본 클래스입니다.

curl_curl_curl을 클릭합니다.php

// This class has all the necessary code for making API calls thru curl library

class CurlHelper {

// This method will perform an action/method thru HTTP/API calls
// Parameter description:
// Method= POST, PUT, GET etc
// Data= array("param" => "value") ==> index.php?param=value
public static function perform_http_request($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    //curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    //curl_setopt($curl, CURLOPT_USERPWD, "username:password");

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

}

그런 다음 언제든지 파일을 포함하여 사용할 수 있습니다(예: any.php).

    require_once("curl_helper.php");
    ...
    $action = "GET";
    $url = "api.server.com/model"
    echo "Trying to reach ...";
    echo $url;
    $parameters = array("param" => "value");
    $result = CurlHelper::perform_http_request($action, $url, $parameters);
    echo print_r($result)

하시면 됩니다.file_get_contents의 http "http"를POST/PUT/DELETE/OPTIONS/HEAD「」에 가세해, 「」에 해 방식GET메서드를 지정합니다.

file_get_contents를 사용하여 PHP에 데이터를 게시하려면 어떻게 해야 합니까?

사실 손님이 많아요.그 중 하나가 페스트입니다. 이것 좀 보세요.또한 이러한 REST 콜은 GET, POST, PUT 및 DELETE 등의 다양한 메서드를 가진 단순한 http 요구입니다.

Symfony를 사용하는 경우 100개까지의 예외를 모두 포함하여 의미 없는 에러 코드 + 메시지를 반환하지 않고 이를 슬로우하는 우수한 rest 클라이언트 번들이 있습니다.

꼭 확인해 주세요.https://github.com/CircleOfNice/CiRestClientBundle

인터페이스가 마음에 듭니다.

try {
    $restClient = new RestClient();
    $response   = $restClient->get('http://www.someUrl.com');
    $statusCode = $response->getStatusCode();
    $content    = $response->getContent();
} catch(OperationTimedOutException $e) {
    // do something
}

모든 http 메서드에서 동작합니다.

서드파티 툴을 사용할 의향이 있는 경우는, https://github.com/CircleOfNice/DoctrineRestDriver 를 참조해 주세요.

이것은 API를 사용하는 완전히 새로운 방법입니다.

우선, 착신 및 발신 데이터의 구조를 정의하는 엔티티를 정의하고, 데이터 소스로 주석을 붙입니다.

/*
 * @Entity
 * @DataSource\Select("http://www.myApi.com/products/{id}")
 * @DataSource\Insert("http://www.myApi.com/products")
 * @DataSource\Select("http://www.myApi.com/products/update/{id}")
 * @DataSource\Fetch("http://www.myApi.com/products")
 * @DataSource\Delete("http://www.myApi.com/products/delete/{id}")
 */
class Product {
    private $name;

    public function setName($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

이제 REST API와 통신하는 것은 매우 간단합니다.

$product = new Product();
$product->setName('test');
// sends an API request POST http://www.myApi.com/products ...
$em->persist($product);
$em->flush();

$product->setName('newName');
// sends an API request UPDATE http://www.myApi.com/products/update/1 ...
$em->flush();

언급URL : https://stackoverflow.com/questions/9802788/call-a-rest-api-in-php

반응형