Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Пример поиска абонентов по коду.

Eсли Если планируется значительное количество запросов, следует установить отдельную копию приложения hoper, чтобы работа с REST API не вызывала задержек в работе операторов через веб-интерфейс.

Основной язык программирования, используемый для разработки интеграций, требующих взаимодействия с API - Python.

Python

Импортируем необходимые модули:

...

Code Block
languagepy
auth_url = urllib_parse.urljoin(hoper_url, 'login')
auth_params = {'session': {'login': hoper_login, 'password': hoper_password}}
response = http_session.post(
    auth_url,
    timeout=http_timeout,
    datajson=json.dumps(auth_params),
)


if response.status_code != HTTPStatus.CREATED:
    logger.error(
        'Auth error ({0}): {1}'.format(response.status_code, response.content),
    )
    sys.exit(1)

Получаем токен, который сервер выдал в теле Логируем ответ сервера и получаем токен из тела ответа

Code Block
languagepy
logger.debug(response.content)
auth_result = json.loads(response.content)
auth_token = auth_result['session']['token']

...

Code Block
languagepy
organizations_url = urllib_parse.urljoin(
    hoper_url, 'search')
response =  'search?result_subtype_id={0}&query={1}'.formathttp_session.get(
    organizations_url,
   search_subtype timeout=http_timeout,
    params={
        'result_subtype_id': search_stringsubtype,
        ),
)
response = http_session.get('query':         organizations_url,    search_string
    timeout=http_timeout,}
)

Если запрос выполнен успешно, по каждой найденной сущности выведем её идентификатор и наименование из результата поиска

...

Code Block
languagepy
titlerest-example.py
linenumberstrue
collapsetrue
"""Hydra REST v2 example."""
import json
import logging
import sys
from http import HTTPStatus
from urllib import parse as urllib_parse

import requests

hoper_url = 'https://hydra.hoper.url/rest/v2/'
hoper_login = '########'
hoper_password = '********'
http_timeout = 60

search_string = 'latera'
search_subtype = 2001

logger = logging.getLogger()
logger.setLevel(logging.INFO)
stdout_logger = logging.StreamHandler()
logger.addHandler(stdout_logger)

http_session = requests.Session()
http_session.headers.update(
    {
        'Content-Type': 'application/json',
        'Accept':       'application/json',
    },
)

auth_url = urllib_parse.urljoin(hoper_url, 'login')
auth_params = {'session': {'login': hoper_login, 'password': hoper_password}}
response = http_session.post(
    auth_url,
    timeout=http_timeout,
    datajson=json.dumps(auth_params),
)

if response.status_code != HTTPStatus.CREATED:
    logger.error(
        'Auth error ({0}): {1}'.format(response.status_code, response.content),
    )
    sys.exit(1)
logger.debug(response.content)

auth_result = json.loads(response.content)
auth_token = auth_result['session']['token']

http_session.headers.update(
    {'Authorization': 'Token token={0}'.format(auth_token)},
)

organizations_url = urllib_parse.urljoin(hoper_url, 'search')
response =  hoperhttp_session.get(
    organizations_url,
    'search?result_subtype_id={0}&query={1}'.format(timeout=http_timeout,
    params={
        'result_subtype_id': search_subtype,
        search_string,'query':     ), ) response = http_session.get(     organizationssearch_url,string
    timeout=http_timeout,}
)

if response.status_code == HTTPStatus.OK:
    search_results = json.loads(response.content)['search_results']
    for entity in search_results:
        logger.info(
            'Customer `{0}`: `{1}`'.format(
                entity['n_entity_id'],
                entity['vc_result_name'],
            ),
        )
else:
    logger.warning(
        'Invalid response ({0}): {1}'.format(
            response.status_code,
            response.content,
        ),
    )


PHP

Задаём параметры подключения к офису оператора связи:

...

Если запрос выполнен успешно, получаем токен из ответа сервера. Если авторизация не выполнилась успешно, завершаем работу скриптаускрипта

Code Block
languagejava
String authToken = "";
if (authResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
  JSONObject authResponseData = new JSONObject(
      EntityUtils.toString(authResponse.getEntity()));
  authToken = authResponseData.getJSONObject("session").getString("token");
} else {
  System.err.println("Auth error (" + authResponse.getStatusLine().getStatusCode() + "): "
      + EntityUtils.toString(authResponse.getEntity()));
  System.exit(1);
}

...

Code Block
languagejava
titlesrc/main/java/RestAPI.java
linenumberstrue
collapsetrue
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

public class RestAPI {

  public static void main(String[] args) {
    String hoperUrl = "https://hydra.hoper.url/rest/v2/";
    String hoperLogin = "########";
    String hoperPassword = "********";
    int httpTimeout = 60;

    String searchString = "latera";
    int searchSubtype = 2001;

    JSONObject authParamsCredentials = new JSONObject();
    authParamsCredentials.put("login", hoperLogin);
    authParamsCredentials.put("password", hoperPassword);
    JSONObject authParams = new JSONObject();
    authParams.put("session", authParamsCredentials);

    RequestConfig config = RequestConfig.custom()
        .setSocketTimeout(httpTimeout * 1000).build();

    try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config)
        .build()) {
      HttpPost authRequest = new HttpPost(hoperUrl + "login");
      HttpEntity stringEntity = new StringEntity(authParams.toString(),
          ContentType.APPLICATION_JSON);
      authRequest.setEntity(stringEntity);
      CloseableHttpResponse authResponse = httpclient.execute(authRequest);

      String authToken = "";
      if (authResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
        JSONObject authResponseData = new JSONObject(
            EntityUtils.toString(authResponse.getEntity()));
        authToken = authResponseData.getJSONObject("session").getString("token");
      } else {
        System.err.println("Auth error (" + authResponse.getStatusLine().getStatusCode() + "): "
            + EntityUtils.toString(authResponse.getEntity()));
        System.exit(1);
      }

      String getUrl = hoperUrl + "search?result_subtype_id=" +
          searchSubtype +
          "&query=" +
          searchString;
      HttpGet searchRequest = new HttpGet(getUrl);
      searchRequest.addHeader("Authorization", "Token token=" + authToken);
      CloseableHttpResponse searchResponse = httpclient.execute(searchRequest);

      if (searchResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        JSONObject searchResponseData = new JSONObject(
            EntityUtils.toString(searchResponse.getEntity()));
        JSONArray searchResults = searchResponseData.getJSONArray("search_results");

        for (int i = 0; i < searchResults.length(); i++) {
          JSONObject row = (JSONObject) searchResults.get(i);
          System.out.println(
              "Customer " + row.getInt("n_entity_id") + ": " + row.getString("vc_result_name"));
        }
      } else {
        System.err.println(
            "Invalid response (" + searchResponse.getStatusLine().getStatusCode() + "): "
                + EntityUtils.toString(searchResponse.getEntity()));
      }

    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}