Modern business processes rarely work in isolation. The 1C accounting system must exchange data with websites, CRM systems, delivery services, banks, and dozens of other services. To do this, APIs are used — software interfaces that allow systems to communicate with each other. Let's figure out how it works and how to start creating integrations in 1C.
What are APIs and why do I need them?
An API (Application Programming Interface) is a set of rules by which one program can request data or functions from another. Imagine you're going to a restaurant. You don't go to the kitchen to cook yourself — you tell the waiter what you want to order, he passes the order to the kitchen, and then brings the finished dish. The API works like this waiter: it takes requests, processes them and returns the result.
Typical 1C integration tasks:
Loading orders from the online store
Sending documents to the bank
Getting exchange rates
Synchronization with CRM systems
Sending data to delivery services
Obtaining information about counterparties from external databases
REST and SOAP: two approaches to creating an API
SOAP — a classic approach
SOAP (Simple Object Access Protocol) is a data exchange protocol that appeared in the late 90s. It uses XML to transmit messages and has a strict structure.
Example of a SOAP request:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetClientInfo xmlns="http://example.com/">
<ClientID>12345</ClientID>
</GetClientInfo>
</soap:Body>
</soap:Envelope>SOAP services are described using WSDL (Web Services Description Language) — a special file that contains all the information about available methods, parameters, and data types. It's like a detailed instruction manual for using the API.
SOAP pros:
Strict typing and data validation
Built-in security support
Support for complex operations and transactions
Standardized error handling
Cons of SOAP:
Bulky XML increases the size of transmitted data
More difficult to learn and configure
Slower due to XML processing
REST is a modern standard
REST (Representational State Transfer) is an architectural style that uses standard HTTP methods. REST is simpler, easier, and faster than SOAP.
Basic HTTP methods in REST:
GET - get data
POST — create a new entry
PUT - update existing record
DELETE - delete entry
Example of a REST request (getting information about the client):
GET https://api.example.com/clients/12345Pros of REST:
Ease of use
Fast work
Compact data (usually JSON)
Easy to test via browser or Postman
Cons of REST:
Less standardization (each API can be arranged in its own way)
No built-in support for complex operations
JSON is a data exchange language
JSON (JavaScript Object Notation) is a text format for transmitting structured data. It has become the standard for REST API due to its simplicity and readability.
Example of JSON data:
{
"clientId": "12345",
"name": "Romashka LLC",
"inn": "7701234567",
"contacts": {
"phone": "+7 495 123-45-67",
"email": "info@romashka.ru"
},
"orders": [
{
"id": "ORD-001",
"date": "2024-12-01",
"amount": 45000
}
]
}JSON is easy to read by a human and is simply processed by software. 1C has built-in tools for working with JSON.
Working with HTTP requests in 1C
To send and receive data via the API in 1C, the HTTPСоединение and HTTPЗапрос objects are used.
Simple GET request
// Establishing a connection with the server
Соединение = Новый HTTPСоединение(
"api.example.com", // server address
443, // port (443 for HTTPS)
, // login
, // password
, // proxy
30, // timeout in seconds
Новый ЗащищенноеСоединениеOpenSSL() // for HTTPS
);
// Creating a request
Запрос = Новый HTTPЗапрос("/clients/12345");
// Sending a request and getting a response
Ответ = Соединение.Получить(Запрос);
// Checking the response code
Если Ответ.КодСостояния = 200 Тогда
ТелоОтвета = Ответ.ПолучитьТелоКакСтроку();
Сообщить(ТелоОтвета);
Иначе
Сообщить("Error: " + Ответ.КодСостояния);
КонецЕсли;POST request with JSON data
// Preparing data
ДанныеJSON = Новый Структура;
ДанныеJSON.Вставить("name", "Vasilyok LLC");
ДанныеJSON.Вставить("inn", "7702345678");
// Convert to JSON
ЗаписьJSON = Новый ЗаписьJSON;
ЗаписьJSON.УстановитьСтроку();
ЗаписатьJSON(ЗаписьJSON, ДанныеJSON);
СтрокаJSON = ЗаписьJSON.Закрыть();
// Creating a request
Запрос = Новый HTTPЗапрос("/clients");
Запрос.Заголовки.Вставить("Content-Type", "application/json");
Запрос.УстановитьТелоИзСтроки(СтрокаJSON);
// Sending
Соединение = Новый HTTPСоединение("api.example.com", 443, , , , 30,
Новый ЗащищенноеСоединениеOpenSSL());
Ответ = Соединение.ОтправитьДляОбработки(Запрос);
// Processing response
Если Ответ.КодСостояния = 201 Тогда
Сообщить("Customer successfully created");
КонецЕсли;JSON parsing in 1C
To read JSON, use ЧтениеJSON:
СтрокаJSON = Ответ.ПолучитьТелоКакСтроку();
ЧтениеJSON = Новый ЧтениеJSON;
ЧтениеJSON.УстановитьСтроку(СтрокаJSON);
Данные = ПрочитатьJSON(ЧтениеJSON);
ЧтениеJSON.Закрыть();
// Now we can access the data
Имя = Данные["name"];
ИНН = Данные["inn"];
Телефон = Данные["contacts"]["phone"];If the JSON structure is known in advance, you can use deserialization into the structure:
ЧтениеJSON = Новый ЧтениеJSON;
ЧтениеJSON.УстановитьСтроку(СтрокаJSON);
Данные = ПрочитатьJSON(ЧтениеJSON, Истина); // Truth = read into the structure
ЧтениеJSON.Закрыть();
API authentication
Most APIs require authentication. The main methods are:
Basic Authentication
Login and password are transmitted in the header:
Запрос = Новый HTTPЗапрос("/api/data");
Логин = "user";
Пароль = "password";
СтрокаАвторизации = Base64Строка(Логин + ":" + Пароль);
Запрос.Заголовки.Вставить("Authorization", "Basic " + СтрокаАвторизации);API Key
The special key is passed in the header or parameter:
Запрос = Новый HTTPЗапрос("/api/data");
Запрос.Заголовки.Вставить("X-API-Key", "your_secret_key");Bearer Token (OAuth)
The access token is obtained by a separate request:
Запрос = Новый HTTPЗапрос("/api/data");
Запрос.Заголовки.Вставить("Authorization", "Bearer " + Токен);Error handling
You always need to provide for error handling:
Попытка
Ответ = Соединение.Получить(Запрос);
Если Ответ.КодСостояния = 200 Тогда
// Successful request
Данные = ПолучитьДанныеИзОтвета(Ответ);
ИначеЕсли Ответ.КодСостояния = 404 Тогда
ВызватьИсключение("Resource not found");
ИначеЕсли Ответ.КодСостояния = 401 Тогда
ВызватьИсключение("Authorization error");
Иначе
ВызватьИсключение("Server error: " + Ответ.КодСостояния);
КонецЕсли;
Исключение
Сообщить("Error while working with API: " + ОписаниеОшибки());
ЗаписьЖурналаРегистрации("Integration.API",
УровеньЖурналаРегистрации.Ошибка,
,
,
ПодробноеПредставлениеОшибки(ИнформацияОбОшибке())
);
КонецПопытки;Working with SOAP in 1C
To work with SOAP services, 1C can automatically create an object based on WSDL:
// Defining SOAP service by WSDL
Попытка
WSОпределения = Новый WSОпределения(
"http://example.com/service?wsdl",
"Login",
"Password"
);
// Creating a proxy to work with the service
WSПрокси = Новый WSПрокси(WSОпределения,
"ServiceNamespace",
"ServiceName");
// Calling the service method
Результат = WSПрокси.GetClientInfo("12345");
Исключение
Сообщить("Error while working with SOAP: " + ОписаниеОшибки());
КонецПопытки;Practical advice
Use constants for addresses and keys. Do not store URLs and API keys directly in the code — put them in constants or settings. This will simplify changing the connection settings.
Log all operations. Log all calls to external APIs: requests, responses, errors. This will help with debugging.
Handle timeouts. External services may be unavailable or slow to respond. Set reasonable timeouts and correctly handle situations when the service is not responding.
Test with Postman. Before writing code in 1C, test the API through Postman or a similar tool. This will help you understand the structure of requests and responses.
Consider API limits. Many services limit the number of requests per unit of time. Provide mechanisms to limit the frequency of requests.
Use asynchronous processing. For mass operations, it is better to use background tasks so as not to block the user's work.
Example of real integration
Let's create a simple integration to get the exchange rate from the website of the Central Bank of the Russian Federation:
Функция ПолучитьКурсВалюты(КодВалюты, Дата)
СтрокаДаты = Формат(Дата, "DF=dd.MM.yyyy");
Соединение = Новый HTTPСоединение("www.cbr.ru", 443, , , , 30,
Новый ЗащищенноеСоединениеOpenSSL());
Запрос = Новый HTTPЗапрос("/scripts/XML_daily.asp?date_req=" + СтрокаДаты);
Попытка
Ответ = Соединение.Получить(Запрос);
Если Ответ.КодСостояния = 200 Тогда
ТелоОтвета = Ответ.ПолучитьТелоКакСтроку();
// Parsing XML
Чтение = Новый ЧтениеXML;
Чтение.УстановитьСтроку(ТелоОтвета);
Пока Чтение.Прочитать() Цикл
Если Чтение.ТипУзла = ТипУзлаXML.НачалоЭлемента
И Чтение.Имя = "Valute" Тогда
ТекКод = "";
ТекКурс = 0;
Пока Чтение.ПрочитатьАтрибут() Цикл
Если Чтение.Имя = "ID" И Чтение.Значение = КодВалюты Тогда
// We found the right currency, let's read the exchange rate
Пока Чтение.Прочитать() Цикл
Если Чтение.Имя = "Value" Тогда
Чтение.Прочитать();
СтрокаКурса = СтрЗаменить(Чтение.Значение, ",", ".");
Возврат Число(СтрокаКурса);
КонецЕсли;
КонецЦикла;
КонецЕсли;
КонецЦикла;
КонецЕсли;
КонецЦикла;
Чтение.Закрыть();
КонецЕсли;
Исключение
Сообщить("Error getting the rate: " + ОписаниеОшибки());
Возврат 0;
КонецПопытки;
Возврат 0;
КонецФункции
// Use
Курс = ПолучитьКурсВалюты("R01235", ТекущаяДата()); // USD
Сообщить("Dollar exchange rate: " + Курс);Conclusion
Integrations with external services are an important part of modern development in 1C. REST APIs with JSON have become the standard due to their simplicity and efficiency, although SOAP is still used in corporate systems. It is better to start with simple GET requests, gradually moving to more complex scenarios with POST, PUT, authentication and error handling.
Having mastered the basic principles of working with HTTP, JSON and API, you will be able to connect 1C to almost any modern service — from online stores to banking systems.
Keep learning!
You can explore this topic and much more in Codice - a platform for learning programming with practical examples and real tasks.
And we also have a cool Telegram channel with a friendly community of developers where you can ask questions, share experiences and keep up to date with new materials!
