Дерево страниц

Сравнение версий

Ключ

  • Эта строка добавлена.
  • Эта строка удалена.
  • Изменено форматирование.
Sv translation
languageru_RU
Информация
iconfalse

Раздел API в административной панели позволяет просматривать описание функций REST API и выполнять запросы пользователей. 

Подробнее про работу с API рассказано на этой странице, а также в видео:

Коннектор виджета
width800
urlhttps://www.youtube.com/watch?v=nhp1aUcmx4c
height400

Чтобы перейти к документации, выберите раздел API в административной панели или перейдите по ссылке

Image RemovedImage Added

Agora REST API

Вы можете использовать эту спецификацию для работы с API-методами с помощью Postman: загрузить.

Что такое API?

API (от англ. application programming interface — интерфейс программирования приложений) — это интерфейс, который дает возможность с помощью специальных команд управлять каким-либо программным обеспечением (например, приложением, сервисом, программой).

Для чего используют API Agora?

Мы предлагаем описание тех методов API, которыми вы сможете оперировать для выполнения таких задач, как:

  • регистрация пользователя;

  • импорт товаров, а также цен и остатков по товарам;

  • получение и отправка заказов, а также обновление их статусов;

  • получение информации о новостях и акциях;

  • получение и создание рекламаций;

  • получение аналитической информации о товарах, заказах, покупателях;

  • получение и отправка сообщений в формах обратной связи или чате

  • и т.д.

Особенности API Agora

Протокол передачи данных

API поддерживает HTTPS протоколы.

Формат запросов

API поддерживает CORS — кросс-доменные запросы.

В API Agora используются запросы.

Авторизация

Запросы требуют API-ключ для авторизации. Чтобы получить ключ, нужно отправить запрос следующий URL для авторизации: . Запрос ожидается в формате и содержит следующие поля:

  • email (не является обязательным, если заполнено поле login);
  • login (не является обязательным, если заполнено поле email);
  • password (обязательное поле)

Формат запроса

В запросах используется формат .

Формат ответа

Форматом ответа по умолчанию является JSON.

Структура ответа

Ответ при запросе списка объектов содержит параметры:

countОбщее количество объектов
nextСсылка на следующую страницу
previousСсылка на предыдущую страницу
resultsСписок, содержащий результаты запроса

Пример ответа см. в разделе "фильтрация запросов".

При запросе объекта по определенному pk ответ содержит один JSON объект с названиями и значениями свойств запрошенного объекта. Пример ответа при запросе на url /news/1/:

Фильтрация запросов

В API Agora есть возможность фильтрации по URL. Чтобы отфильтровать получаемые данные, нужно в query-параметры url передать поле для фильтрации и нужное значение. Пример запроса с фильтрацией новостей.

URL: https://api-cloud.agora.ru/api/rest/v1/news/?title=Тест

Ответ:

Ошибки

Все ошибки представляются в виде человеко- и машиночитаемого статуса. Тело ответа содержит более детальную информацию об ошибке и формируется в зависимости от её типа. Большая часть ошибок содержит в теле ключ "detail". Пример:

Ошибки валидации, однако, содержат ключи, которые соответствуют полям запроса, либо "non_field_errors"в том случае, если ошибка не завязана на значении какого-то конкретного поля запроса. Пример:

Описание используемых статус кодов:

200Ok
201Created
400Bad request
401Unauthorized
403Forbidden
405Method not allowed
500Internal server error

Отправка тестового запроса

Для проверки работы API можно отправить тестовый запрос из соответствующего подраздела документации:

  1. Выберите нужный вам метод API в панели навигации слева.
  2. Нажмите на кнопку Попробовать в правой части экрана.

  3. Откроется форма заполнения полей запроса. Во вкладке Request заполните все необходимые поля.

  4. При необходимости добавьте в раздел Security полученный ранее ключ авторизации.

  5. Нажмите на кнопку Отправить.

  6. Также можно отредактировать запрос и отправить его заново.

  7. Полученный ответ отобразится во вкладке Response.
Sv translation
languageen
Информация
iconfalse

The API section in the administrative panel allows you to view descriptions of REST API functions and fulfill user requests.

To go to the documentation, select the API section in the admin panel or follow the link.

Image Added

Agora REST API

You can use this specification to work with API methods using Postman: download.

What is an API?

API (application programming interface) is an interface that makes it possible to control any software (for example, an application, service, program) using special commands.

What is the Agora API used for?

We offer a description of the API methods that you can use to perform tasks such as:

  • User registration;
  • import of goods, as well as prices and balances of goods;
  • receiving and sending orders, as well as updating their statuses;
  • receiving information about news and promotions;
  • receiving and creating complaints;
  • obtaining analytical information about products, orders, customers;
  • receiving and sending messages in feedback forms or chat
  • etc.

Agora API Features

Data transfer protocol

The API supports HTTPS protocols.

Request Format

The API supports CORS - cross-domain requests.

The Agora API uses Image Addedqueries

Authorization

Requests require an API key for authorization. To get the key, you need to send a request to the following URL for authorization: Image Added. The request is expected in the format Image Added and contains the following fields:

  • email (not required if the login field is filled in);
  • login (not required if the email field is filled in);
  • password (required field)

Request Format

Requests use the format Image Added.

Response Format

The default response format is JSON.

Response structure

The response when requesting a list of objects contains the following parameters:

countTotal number of objects
nextLink to next page
previousLink to previous page
resultsList containing query results

For an example response, see the "Request Filtering" section.

When requesting an object for a specific pk, the response contains one JSON object with the names and values of the properties of the requested object. An example of a response to a request for url /news/1/:

Image Added

Request filtering

The Agora API has the ability to filter by URL. To filter the received data, you need to pass the filtering field and the desired value to the url query parameters. An example of a news filtering query.

URL: https://api-cloud.agora.ru/api/rest/v1/news/?title=Тест

Answer:

Image Added

Errors

All errors are presented as human- and machine-readable status. The response body contains more detailed information about the error and is formed depending on its type. Most errors contain the "detail" key in the body. Example:

Image Added

Validation errors, however, contain keys that correspond to request fields, or "non_field_errors" if the error is not related to the value of a specific request field. Example:

Image Added

Description of the status codes used:

200Ok
201Created
400Bad request
401Unauthorized
403Forbidden
405Method not allowed
500Internal server error

Sending a test request

To check the operation of the API, you can send a test request from the corresponding subsection of the documentation:

  1. Select the API method you need from the navigation bar on the left.
    Image Added
  2. Click on the Try it button on the right side of the screen.
    Image Added
  3. A form for filling out the request fields will open. In the Request tab, fill in all the required fields.
    Image Added
  4. If necessary, add the previously obtained authorization key to the Security section.
    Image Added
  5. Click on the Send button.
    Image Added
  6. You can also edit the request and resend it.
    Image Added
  7. The received response will be displayed in the Response tab.
    Image Added

Our service provides the ability to connect to an external API (REST API), which provides the ability to integrate with strict services. API documentation is available at the following address: https://compras1.agorab2b.com/api/rest/docs
For review, you can use the test project.
For ease of use, we will describe the process of executing one API request, focusing on which you can execute the rest.
Take a callback request as an example: callback_request
To execute API methods, click on the name of the API method and enter the corresponding request parameters in the drop-down list:

Image Removed

Having specified all the necessary data of the request, it is enough to click on the Try it out button to initiate the execution of the request:

Image Removed

If the request is successfully processed, you will see a notification of the form:

Image Removed

The Response Body section will display the array of data that was passed to the portal:

Image Removed

To check the correctness of the completed request, just go to the administrator panel in the Request for a call back section

Image Removed

Having opened the corresponding section, you will see information about the request we are executing:

Image Removed

By analogy with the above API method, you can execute any of the above list of API requests: http://project_address.ru/api/rest/docs
(информация) If you encounter difficulties/errors while using the API, you should write to the technical support at help@agora.ru and you will definitely be helped.
Sv translation
languagept_BR
Информация
iconfalse

A seção API no painel de administração permite que você exiba a descrição das funções da API REST e atenda às solicitações do usuário.

Para acessar a documentação, selecione a seção API no painel de administração ou siga o link.

Image Added

Agora REST API

Você pode usar essa especificação para trabalhar com métodos de API usando Postman: Download.

O que é uma API?

API (Application Programming Interface) é uma interface que torna possível controlar qualquer software (por exemplo, um aplicativo, serviço, programa) usando comandos especiais.

Para que servem as APIs do Agora?

Oferecemos uma descrição dos métodos de API que você pode usar para executar tarefas como:

  • cadastro de usuários;
  • importação de mercadorias, bem como preços e saldos de mercadorias;
  • recebimento e envio de pedidos, bem como atualização de seus status;
  • receber informações sobre novidades e promoções;
  • recebimento e criação de reclamações;
  • obtenção de informações analíticas sobre produtos, pedidos, clientes;
  • Receber e enviar mensagens em formulários de feedback ou chat
  • etc.

Características da API Agora

Protocolo de Transferência de Dados

A API oferece suporte a protocolos HTTPS.

Formato do pedido

A API oferece suporte a CORS – solicitações entre domínios.

A API do Agora usa Image Addedconsultas.

Autorização

As solicitações exigem uma chave de API para autorização. Para obter a chave, você precisa enviar uma solicitação para a seguinte URL de autorização: Image Added. A solicitação é esperada no formato Image Added e contém os seguintes campos:

  • email (opcional se o campo de login estiver preenchido);
  • login (opcional se o campo de e-mail estiver preenchido);
  • password (obrigatório)

Formato do pedido

As solicitações usam o formato Image Added.

Formato da resposta

O formato de resposta padrão é JSON.

Estrutura de Resposta

A resposta ao solicitar uma lista de objetos contém os seguintes parâmetros:

countNúmero total de objetos
nextLink para a próxima página
previousLink para a página anterior
resultsUma lista que contém os resultados de uma consulta

Para obter um exemplo de resposta, consulte Filtrando solicitações.

Quando um objeto é consultado em um pk específico, a resposta contém um único objeto JSON com os nomes e valores de propriedade do objeto solicitado. Exemplo de uma resposta a uma solicitação para url /news/1/:

Image Added

Filtrando solicitações

A API do Agora tem a capacidade de filtrar por URL. Para filtrar os dados recebidos, você precisa passar o campo para filtragem e o valor desejado para os parâmetros de consulta da url. Um exemplo de uma consulta com filtragem de notícias.

URL: https://api-cloud.agora.ru/api/rest/v1/news/?title=Тест

Responder:

Image Added

Erros

Todos os erros são representados na forma de um status legível por humanos e máquinas. O corpo da resposta contém informações mais detalhadas sobre o erro e é gerado dependendo de seu tipo. A maioria dos erros contém uma chave de "detalhe" no corpo. Exemplo:

Image Added

Os erros de validação, no entanto, contêm chaves que correspondem a campos de consulta ou "non_field_errors" se o erro não estiver vinculado ao valor de um campo de consulta específico. Exemplo:

Image Added

Descrição dos códigos de status utilizados:

200Ok
201Created
400Bad request
401Unauthorized
403Forbidden
405Method not allowed
500Internal server error

Enviar uma solicitação de teste

Para verificar o funcionamento da API, você pode enviar uma solicitação de teste da subseção correspondente da documentação:

  1. Selecione o método de API desejado na barra de navegação esquerda.
    Image Added
  2. Clique no botão Try it no lado direito da tela.
    Image Added
  3. Um formulário para preenchimento dos campos de solicitação será aberto. Na guia Request, preencha todos os campos obrigatórios.
    Image Added
  4. Se necessário, adicione a chave de autorização recebida anteriormente à seção Security.
    Image Added
  5. Clique no botão Send .
    Image Added
  6. Você também pode editar a solicitação e reenviá-la.
    Image Added
  7. A resposta será exibida na guia Response.
    Image Added

Nosso serviço oferece a capacidade de conectar uma API externa (REST API), que fornece a capacidade de se integrar a serviços rigorosos. A documentação da API está disponível em: http:// Project_address.ru/api/rest/docs

(информация) A conexão da funcionalidade é realizada mediante solicitação de suporte técnico: help@agora.ru ou através de um personal manager. 

Para familiarização, você pode usar o projeto de teste.

Para facilitar o uso, descreveremos o processo de execução de uma solicitação de API, com foco em que você pode executar os outros. 

Como exemplo, vamos fazer um pedido de iniciação de retorno de chamada: callback_request

Para executar os métodos de API, clique no nome do método API e digite os parâmetros de consulta apropriados na lista de drop-down:

Image RemovedTendo especificado todos os dados de solicitação necessários, basta clicar no botão Try it out para iniciar a execução da solicitação:

Image RemovedSe a solicitação for processada com sucesso, você verá uma notificação do seguinte formulário:

Image RemovedA seção Response Body exibirá o conjunto de dados que foi carregado no portal:

Image RemovedPara verificar a correção da solicitação concluída, basta ir ao painel administrativo na seção solicitação de retorno de chamada

Image RemovedAo abrir a seção correspondente, você verá informações sobre a solicitação que estamos executando:

Image Removed

Por analogia com o método de API acima, você pode executar qualquer uma das seguintes listas de API de solicitação http://адрес_проекта.ru/api/rest/docs:

(информация) Se houver dificuldades/erros ao usar a API, você precisa escrever para o suporte técnico no endereço: help@agora.ru e eles definitivamente irão ajudá-lo.