Работаем с API, часть 1

Работаем с API, часть 1

Доброе время суток, уважаемые читатели!

В нашу техподдержку часто обращаются с просьбой показать пример работы API. Поэтому в данной статье мы с вами создадим очень простое приложение, которое будет получать позицию сайта по ключу в Гугл или Яндекс и выводить результат в окне.
Приложение будет иметь простейший интерфейс:
8bm7v_181208235002.png

Описывать код HTML, CSS и JS не буду, в виду его максимальной простоты, и просто выложу его в спойлер.
HTML:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Работаем с API</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
              <div class="container">
                    <form>
                        <label for="key">Ключ</label>
                        <input type="text" id="key" name="key">
                        <label for="site">Сайт</label>
                        <input type="text" name="site" id="site">
                        <br>
                        <input class="but" type="button" value="Проверить в Google" name="but" onclick="check_google();">
                         <input class="but" type="button" value="Проверить в Yandex" name="but" onclick="check_yandex();">
                    </form>
                </div>
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
 <script src="script.js"></script>
</body>
</html>
Код:
.container{
    display: flex;
    align-items: center;
    justify-content: center;
}
label{
    display: block;
}
.but{
    margin-top: 5px;
}
Код:
function check_google(){
    $.ajax({
             type: "POST",
             url: "action.php",
            // data: {idParts:idParts,oper:'D24'},
             data: {key:$('#key').val(),site:$('#site').val(),oper:'Google'},
             success: function(msg) {
                  alert(msg);
                  //$('#results').html(msg);
             }
         });
}
function check_yandex(){
    $.ajax({
             type: "POST",
             url: "action.php",
            // data: {idParts:idParts,oper:'D24'},
             data: {key:$('#key').val(),site:$('#site').val(),oper:'Yandex'},
             success: function(msg) {
                  alert(msg);
                  //$('#results').html(msg);
             }
         });
}
PHP:
<?php
use API\EngineWeb AS EngineWeb;
spl_autoload_register();
$engine =new EngineWeb('http://127.0.0.1:9091/API','','a-parser.com парсер');
 switch($_POST['oper']){
        case 'Google':
           $engine->RequestGoogle();
        break;
        case 'Yandex':
           $engine->RequestYandex();;
        break;
    }

А рассмотрим мы с вами класс который и работает с API.
Назовем его EngineWeb
Код:
class EngineWeb {
    protected  $pass,$path,$google,$yandex;
    function __construct($url,$password = '',$query) {
        $this->pass = $password;
        $this->path = $url;
        $this->google = $this->GetGoogleJSON($query);
        $this->yandex = $this->GetYandexJson($query);
    }
Методы GetGoogleJSON и GetYandexJSON практически идентичны и формируют json для отправки.

Давайте рассмотрим один из них. Создадим пресет для получения позиции сайта в индексе Google через интерфейс.
p9p6q_181209012531.png


Следующим нашим шагом будет получение опций для нашего JSON:
jsgmi_181209012825.png


Теперь наш метод приобретает вид:
Код:
/*метод формирующий json для запроса*/
    function  GetGoogleJSON($query){
        $json = json_encode([
           'action' => 'oneRequest',
           'password' => $this->pass,
            'data' => [
               'preset' => 'default',
               "configPreset" => "100 Threads",
               'parser' => 'SE::Google::Position',
               'query' => $query ,
               'options' => [
                  [
                    'type' => 'override',
                    "id" => "proxyretries",
                    "value" => "100",
                  ],
                  [
                    'type' => 'override',
                    "id" => "linksperpage",
                    "value" => 50,
                  ],
                  [
                    'type' => 'override',
                    "id" => "Util_ReCaptcha2_preset",
                    "value" => "Antigate",
                  ],
                  [
                     "type" => "override",
                     "id" => "formatresult",
                     "value" => "\$position\\n"
                  ],
               ],
              ]
      ]);
      return $json;
    }
Как видно в описании метода, использовать мы будем метод oneRequest. Примеры для работы с другими методами, будут приложены в следующих статьях описывающих работу с API.

Теперь, когда у нас есть JSON c нужными данными, реализуем метод, который будет его отправлять с помощью CURL:
Код:
 /*метод отправляющий запрос*/
    function RequestGoogle(){
      $ch = curl_init($this->path);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $this->google);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($this->google)));
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain; charset=UTF-8'));
      $response = curl_exec($ch);
       curl_close($ch);
      $response = json_decode($response, true);
      echo $response['data']['resultString'];
    }

Проверяем:
vnsiw_181209015926.png

Готово.

В следующей статье рассмотрим работу с addTask.
Автор
Support Денис
Просмотры
17
Первый выпуск
Обновление

Рейтинги

0,00 звёзд Оценок: 0

Ещё ресурсы от Support Денис

Назад
Верх