API для работы с хостингом позволяет автоматизировать
управление ресурсами и анализ данных.
Примеры использования API хостинга:
Доступ к API хостинга автоматически активен в любом оплаченном тарифном плане. Для тестовых или бесплатных аккаунтов API не работает.
Доступ происходит по протоколу HTTPS по базовому адресу https://www.1gb.ru/api/ или https://api.1gb.ru/api/. Параметры большинства запросов можно передавать с помощью GET или POST параметров. Ответ содержит объект или массив объектов по стандарту JSON.
Адреса www.1gb.ru и api.1gb.ru с целью вызова API равноценны, просто они поддерживают разные наборы HTTPS шифрования. Если у вас современный проект, лучше использовать api.1gb.ru, если старый, то www.1gb.ru.
Перед началом работы с API требуется получить token для дальнейшей авторизации.
В личном кабинете найдите раздел "полный список функций", "Смена главного пароля аккаунта, мультифактор, ключи доступа". Там есть создание API token-а одной кнопкой. Это предпочтительный и самый простой путь для обычных ситуаций.
Через API Это делается следующим образом (приведены примеры использования GET параметров):
В данном вызове, одноразовый пароль - это код ограниченного времени действия, который виден на странице кабинета "пароли на ресурсы". Это не пароль от личного кабинета.
Последний запрос возвращает string, в нем token, его нужно запомнить и использовать для последующей авторизации. Token утрачивает силу при смене главного пароля аккаунта, существует также возможность деактивировать отдельные token-ы со страницы кабинета "смена главного пароля аккаунта".
Примеры дальнейших запросов:
Ответы API с HTTP кодом 200 обозначают успешное исполнение операции. В ответном JSON может содержаться два разных типа:
Большинство команд API, таких как /list, возвращают внутренние структуры из базы данных хостинга, которые содержат сотни полей. Документировать их трудоемко, поэтому рекомендуем просто смотреть на вывод соответствующих команд и анализировать структуры данных по очевидным названиям полей.
В том случае, если трактовка полей вызывает затруднения, пишите на support@1gb.ru, поможем разобраться.
https://www.1gb.ru/api + адрес из списка ниже. Обязательный параметр каждой команды - _token_. Остальные параметры приведены после команды. В квадратных скобках - не обязательные. В круглых - примеры или умолчания.
Адрес актуального формата API (приведен далее): https://www.1gb.ru/services_api.php.txt
API Schema /endpoint (https://hosting-website-url/api/endpoint?_token_=<API access token>) <endpoint description> &option = GET / POST paramter (&option=value) [&option] = paramter is optional /auth/start API-driven token generation procedure. Alternative is to create a token from the Control Panel. &login /auth/login API-driven token generation procedure. Alternative is to create a token from the Control Panel. &login &salt &response [&user_agent] /logoff /auth/logoff Destroy current token (NOT the current session). Use with care - this cannot be undone. You may lose access. /c2dmkey/set Internal usage, do not call. &_key_ /gcmkey/set Internal usage, do not call. &_key_ /iospushkey/set Internal usage, do not call. &_key_ /overview Plaintext general overview of global account status and descriptive list of all account resources. AI agents should start here. /overview/passwords Plaintext general overview of all resource passwords. /billing/info Legal data of the account. /billing/limits Lists current Hosting Plan limits and resource usage. /billing/balance Returns current account balance. Typical payment credit time is 1 minute. /billing/balance.lic Returns current account balance for Licensing contract (obsolete). /billing/debt Returns negative balance metrics (days of debt, etc). /updates/list Lists account events. [&_key_] - first ID or 0 to show all (some dynamic limit will be introduced) /updates/last Last account event ID. /vds/list Lists account servers of all types (including Digital DC and Hardware rent). Includes all the properties and logins / passwords (if known). [&_key_] - /vds/list|id - filter if only one server is needed /vds/templates-list Lists possible VDS server templates and their popularity. /vds/create Create Linux KVM VDS or HyperVPS VDS. Typical creation time is 10 - 30 minutes. [&type] (vds.dynamic) vz1|vz2|vz3|vz4|vz5|vds.dynamic|vds.dynamic.nv [&cr_hvmem] (2048) [&cr_hvdsk] (30) [&cr_hvcpu] (2) [&template] (win2012R2x64) [&force_memo] [&hv_1gb_panel_version] [&panel_install] - 1|0 [&cr_ssd1] - 1|0 [&cr_hv_all_system] - 1|0 /vds/update Adjust Linux KVM VDS or HyperVPS VDS parameters. Typical propagation time is 5 - 10 minutes. &_key_ - /vds/list|id [&cr_hvmem] (2048) [&cr_hvdsk] (30) [&cr_hvcpu] (2) /vds/reboot Reboot server of all types (including Digital DC and Hardware rent). Typical execution time is 3 - 5 minutes. &_key_ - /vds/list|id /vds/online Internal usage, do not call. &_key_ - /vds/list|id &online - 1|0 /vds/delete Delete server of all types (including Digital DC and Hardware rent). &_key_ - /vds/list|id [&force_critical] - 1|0 /vds/ip/list List IP addresses bound to servers of all types (including Digital DC and Hardware rent). [&_key_] - /vds/list|id /vds/ip/add Add new public IP to the server (random IP from the pool). Platform do not manage OS inside server - adjustments to IP configuration needed in the customer OS. &_key_ - /vds/list|id /vds/ip/delete Delete the IP from the server. Platform do not manage OS inside server - adjustments to IP configuration needed in the customer OS. &_key_ - /vds/list|id - owning server &del_ip - IP address (text form) /email/list List mailboxes. Includes login, password, mail server addresses, Webmail link. /email/add Create mailbox. Typical creation time is 5 - 10 minutes. &add_email /email/delete Delete mailbox. &_key_ - /email/list|id /email/alias/list List email aliases. /email/alias/add Create email alias. Typical creation time is 5 - 10 minutes. &add_email_alias (string, from) &add_email_mail (string, to) /email/alias/delete Delete email alias. &_key_ - /email/alias/list|id /website/list List all Websites and properties, including login / password (if known). /website/add Create new Website and base DNS record in hosters home domain for instant access. Typical creation time is 3 - 5 minutes. &name - website name (temp subdomain), keep simple, unique and short &srv_type (avoid Frankfurt if not explicitely told to do so) - 99901 Best for PHP (modern PHP) (recommended default for LAMP) 99902 Best for ASP, ASP.NET (recommended) 99903 Best for Static Content 8 ASP.NET 2 - 3.5 99904 ASP.NET 4+, .NET, .NET .Core (recommended default for Windows IIS) 1 Legacy ASP + .NET 2 - 3.5 4 mod_php 5.2 9 mod_php 5.3 10 mod_php 5.4 11 mod_php 5.5 12 mod_php 5.6 13 mod_php 7.0 15 mod_php 7.1 16 mod_php 7.2 17 mod_php 7.3 18 mod_php 7.4 (recommended) 19 mod_php 8.0 20 mod_php 8.1 21 mod_php 8.2 22 mod_php 8.3 23 mod_php 8.4 24 mod_php 8.5 (recommended) 5 PHP - FastCGI 6 PHP - CGI (STRONGLY not recommended) 20008 Frankfurt - .NET 2 - 3.5 29994 Frankfurt - .NET 4+ (recommended) 2004 Frankfurt - mod_php 5.2 2009 Frankfurt - mod_php 5.3 2010 Frankfurt - mod_php 5.4 2011 Frankfurt - mod_php 5.5 2012 Frankfurt - mod_php 5.6 2013 Frankfurt - mod_php 7.0 2015 Frankfurt - mod_php 7.1 2016 Frankfurt - mod_php 7.2 2017 Frankfurt - mod_php 7.3 2018 Frankfurt - mod_php 7.4 (recommended) 2019 Frankfurt - mod_php 8.0 2020 Frankfurt - mod_php 8.1 2021 Frankfurt - mod_php 8.2 (recommended) 2005 Frankfurt - PHP - FastCGI /website/set-php-version Set Website PHP version. Typical propagation time depend on server type and can be within 3-5 minutes to 1-2 hours. &_key_ - /website/list|id &version - string or number in the form of 7.4, 8.0, 8.5, etc. /website/reset-password Reset Website password. Can be used to get new password if current is not known. Typical propagation time is 3 - 5 minutes. &_key_ - /website/list|id /website/delete Delete Website. &_key_ - /website/list|id /ftp/list Internal usage, do not call. /ftp/delete Internal usage, do not call. &_key_ - /ftp/list|id /dns/list List domains, subdomains, and Website bindings. /dns/add Create domain (add_dns_zone) or subdomain (add_dns_record + add_dns_zone). Typical propagation time is 30 - 60 minutes. &add_dns_zone [&add_dns_record] [&iis_site_for_dns] - /website/list|id OR "ip_a.b.c.d" string to bind to server [&bind_only] - 1|0 /dns/overview WHOIS, registrar, basic dig / records analysis, prolong status description of the domain. &_key_ - /dns/list|id /dns/bind Bind domain name to the Website of server, or unbind from the Website or server. Typical propagation time is 30 - 60 minutes. &_key_ - /dns/list|id [&dns_to] - /website/list|id OR "ip_a.b.c.d" string to bind to server, or 0 to unbind. /dns/delete Delete domain name. &_key_ - /dns/list|id /dns/zone/set-managedmx Alter the setting that hosting should manage MX record on the domain. Enabling managed MX effects in 1 hour typical. Disabling managed MX should be followed by raw- calls to set desired MX. &_key_ - /dns/list|id &upd_managed_mx - 1 &managed_mx - 1|0 - add/keep/update (1) or delete (0) hosting-managed root MX record /dns/zone/raw-list Dig for the zone. The dig source is hosting zone authority. Public observed records will settle to this within DNS propagation time (30 - 60 minutes typical). &_key_ - /dns/list|id /dns/zone/raw-update Edit zone file. DO NOT edit records associated with the managed bindings (see /dns/list fields such as iis_id, vds_ip_assigned_ip, ssl_ip_assigned_ip, redirect_http) - will be overwritten later. Unbind first. Typical propagation time is 30 - 60 minutes. &_key_ - /dns/list|id [&s_del] = 1 to delete record, DO NOT specify ANY s_del to create record [&s_add] = 1 to create record, DO NOT specify ANY s_add to delete record &dns_type = A,MX,CNAME,AAAA,NS,TXT,SRV &dns_name = record name or @ for root &dns_value = record content, dnscmd.exe format (A: [ip], CNAME: [name], MX: [priority] [target]) /database/list List all MySQL / Postgres databases and properties, including login / password (if known). /database/add Create new MySQL / Postgres database. Propagation time - instant. &name - DB name, keep simple, unique and short &type - 9990 - latest MySQL version (most likely 8+) 9991 - latest Postgres version (most likely 18+) /database/reset-password Reset database password. Can be used to get new password if current is not known. This will break current running apps, so better approach to search the password in config files first or ask the user. Propagation time - instant. &_key_ - /database/list|id /database/delete Delete database. &_key_ - /database/list|id /mssql/list List all Microsoft SQL databases, including login / password (if known). /dns/prolong/list List domain names that are subject to prolong in near future. [&show_all - 1|0] - display all names, even if the prolong date is not due /chat/key Internal usage, do not call.
|
Полезный совет |
API хостинга функционирует уже много лет для поддержки различных сценариев, таких как массовые услуги для VDS клиентов или работа наших приложений Android / IOS. Теперь мы решили предоставить к этим API публичный доступ. Текущий функционал API не покрывает 100% возможностей хостинга, но мы готовы быстро расширить его для нужного функционала буквально в считанные дни. Если у вас есть реальная необходимость в автоматизации каких-то конкретных операций, отсутствующих в текущих функциях или пока не опубликованных здесь, смело пишите на support@1gb.ru. | |