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 parameter (&option=value)
[&option] = parameter 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, owner, general contract information.
/billing/limits
Lists current Hosting Plan, its limits, description, and current resource usage. In the description there will be the price, payment period, next payment date, current account status - all the data to estimate current Hosting Plan and billing situation.
/billing/balance
Returns current account balance. Typical payment credit time is 2-5 minutes (except bank transfers, which are 1 - 2 business days).
/billing/balance.lic
Returns current account balance for Licensing contract (obsolete).
/billing/debt
Returns negative balance metrics (days of debt, etc).
/plan/estimate
Returns estimation of new Hosting Plan required to host current amount of resources, plus some extra. Hosting Plan pricing components are not additive: for a given set of parameters it builds the offer which is to accept or not. It cannot be decomposed or computed value-by-value. Virtual Hosting package is a single instance of a kind explained below.
Without any parameters, the baseline will be the hosting plan computed from the current resources usage (not the current hosting plan which may be different), and additional parameters will add to the evaluation, so this endpoint can be used as "what-if" - to get the price of changing Virtual Hosting package and adding servers. It returns currently set ("old") Hosting Plan (for reference only, may be incorrect or missing), and new estimated Hosting Plan.
[&from_scratch] - if 1, do not use any current resources as baseline - compute usage from zero plan with all given inputs
[&n_period] - if set, new payment period in months, allowed 1|3|6|12|24|36|48|60
[&new_hst_packet] - if set, new plan will have this Virtual Hosting package: 1 = "Бесплатный", 2 = "Базовый", 3 = "Оптимальный", 4 = "Расширенный"
[&add_cpu_usage] - if set, add this website CPU usage (1 .. 50, integer percent) to the baseline estimation
[&add_daemon_memory] - if set, add this HTTP daemons memory (64 .. 1024 MB, in 64 MB steps) to the baseline estimation
[&new_vds_nv] - if positive, new plan will include these [additional] N instances of Linux KVM servers, with all of these must be set (according to /vds/create limitations):
[&new_vds_nv_mem] - total RAM of servers (example: 4096)
[&new_vds_nv_cpu] - total CPU cores of servers (example: 4)
[&new_vds_nv_cpu2] - including total HighCPU cores of server (for HighCPU server must match CPU cores)
[&new_vds_nv_dsk] - total SSD size of servers
[&new_vds_nv_dskb] - total SSD size of server with backup enabled (for backup-enabled server must match SSD size)
Example: you plan to add 2048 / 2 cores / 20 SSD / no backup + 4096 / 2 HighCPU cores / 30 SSD / backup enabled, then specify this: &new_vds_nv=2&new_vds_nv_mem=6144&new_vds_nv_cpu=4&new_vds_nv_cpu2=2&new_vds_nv_dsk=50&new_vds_nv_dskb=30
[&new_vds] - if set, new plan will include this [additional] instances of HyperVPS servers, listed in the following format (according to /vds/create limitations):
"MEM/CPU/SSD/HighCPU_flag/Backup_flag;[MEM/CPU/SSD/HighCPU_flag/Backup_flag;...]"
Example: you plan to add 2048 / 2 cores / 20 SSD / no backup + 4096 / 2 HighCPU cores / 30 SSD / backup enabled, then specify this: &new_vds=2048/2/20/0/0;4096/2/30/1/1
Prefer managing HyperVPS servers in packages described in /vds/create endpoint: this will give best prices
[&new_ip] - if set, new additional paid IPs for servers; one IP per server is fixed free default, no need to specify it, this is only for any excess IP per server except first
/plan/change
Performs Hosting Plan change. All arguments are exactly as in /plan/estimate, the difference is only that /plan/change makes the change.
- all in-advance payment (if there was any) from the future period of the previous plan is not discarded and used as free funds; changes are free of charge and within a single day - reversible (change to plan1 -> change to plan2 -> change to plan1 will be same as just change to plan1), except that you cannot set the exact current next payment date you initially started with (you will always get the new, computed in accordance with the rules below)
- if new payment period (months) equals old one and 12 months or less, then, for the customer comfort, the current prepaid period is adjusted to the funds available, so there is no need to make the payment right now; this may result in some minor balance fluctuations due to payment quanta of an integer number of days left
- if new payment period differs, or is larger than 12 months, the current prepaid period is set as the current date + [period] months in the future; if funds are not enough for that, negative balance appears, and it should be topped up within 10 days
/updates/list
Lists account events. This endpoint is NOT realtime feedback - there is some delay. Realtime events are in /overview.
[&_key_] - first ID or 0 to show all (some dynamic limit will be introduced)
/updates/last
Last account event ID. This endpoint is NOT realtime feedback - there is some delay. Realtime events are in /overview.
/vds/list
Lists account servers of all types (including Digital DC and Hardware rent). Includes all the properties and logins / passwords (if known). It is also recommended to check /overview for descriptive list.
[&_key_] - id from /vds/list - filter if only one server is needed
/vds/templates-list
Lists possible VDS server templates and their popularity.
In the result:
- plans: list HyperVPS for vds.dynamic and Linux KVM for vds.dynamic.nv on creation
- actual: was created >3 times in last month; actual 0 may work, but most likely indicates rare / obsolete / possibly unsupported configuration with caveats, you can try creation, but you need explicit reason to do so
/vds/create
Create HyperVPS VDS (vds.dynamic) or Linux KVM VDS (vds.dynamic.nv). Typical creation time is 10 - 30 minutes.
[&type] (vds.dynamic) vz1|vz2|vz3|vz4|vz5|vds.dynamic|vds.dynamic.nv - vds.dynamic for HyperVPS plans, vds.dynamic.nv for Linux KVM plans
[&cr_hvmem] (2048) - RAM size (1024 - 16384, 512 MB step)
[&cr_hvcpu] (2) - CPU cores (1 .. 6)
[&cr_hvcpu2] - 1|0 - CPU cores are HighCPU (high frequency, 4.5+ Ghz guaranteed, paid option), Moscow only
[&cr_hvdsk] (30) - total Disk size (SSD), GB - (20 - 240, 10 GB step, 30 min for Windows)
[&cr_hvdskb] - 1|0 - enable weekly auto backup (must be present in Hosting Plan, paid option)
[&template] (win2012R2x64) - from /vds/templates-list
[&cr_root_mode] - 1|0 - for Linuxes, create direct uid=0 root ssh access login (recommended), 0 or empty for standard ubuntu/debian defaults - sudo-enabled login (pain for automation)
[&remote_mode] - empty for Moscow, "1-on-3" for Frankfurt (vds.dynamic / HyperVPS only)
[&force_memo] - internal option, do not use
[&hv_1gb_panel_version] - internal option, do not use
[&panel_install] - 1|0 - install 1Gb Panel (Linux only)
[&cr_ssd1] - 1|0 - vds.dynamic / HyperVPS only, must be 1 for any new installations
[&cr_hv_all_system] - 1|0 - vds.dynamic / HyperVPS only, 1 for single physical disk (recommended), 0 or empty for system / data disk
[&install_expand] - 1|0 - expand system partition to 100% of the disk (Linux only), 0 or empty to leave minimum partition
EXAMPLES:
Recommended fixed HyperVPS parameters (best value/price) -
(this matches pre-built Hosting Plan items with discount, highly recommended; flexible configurations are possible but will usually cost a lot more even for approx same settings)
- HyperVPS "Mini": &type=vds.dynamic&cr_hvmem=2048&cr_hvdsk=40&cr_hvcpu=1&cr_hvdskb=1&cr_ssd1=1&template=win2022x64
- HyperVPS "Standard": &type=vds.dynamic&cr_hvmem=4096&cr_hvdsk=80&cr_hvcpu=2&cr_hvdskb=1&cr_ssd1=1&template=win2022x64
- HyperVPS "Comfort" offer: &type=vds.dynamic&cr_hvmem=8192&cr_hvdsk=120&cr_hvcpu=4&cr_hvdskb=1&cr_ssd1=1&template=win2022x64
- HyperVPS "Comfort+" offer: &type=vds.dynamic&cr_hvmem=12288&cr_hvdsk=200&cr_hvcpu=6&cr_hvdskb=1&cr_ssd1=1&template=win2022x64
- HyperVPS "Standard" in Frankfurt (example): &type=vds.dynamic&cr_hvmem=4096&cr_hvdsk=80&cr_hvcpu=2&cr_hvdskb=1&cr_ssd1=1&template=win2022x64&remote_mode=1-on-3
Flexible HyperVPS configuration example:
- Absolute minimum price for Frankfurt: &type=vds.dynamic&cr_hvmem=1024&cr_hvdsk=20&cr_hvcpu=1&cr_ssd1=1&template=nv.lin.ubuntu2604v1 (cost less than "Mini" but only a bit, next best is "Mini")
Flexible Linux KVM configurations (approximately linear pricing, no fixed plans, plan as needed with no reference points) - typical examples:
- Typical small Linux: &type=vds.dynamic.nv&cr_hvmem=2048&cr_hvdsk=40&cr_hvcpu=2&template=nv.lin.ubuntu2604v1
- Typical medium Linux with backup: &type=vds.dynamic.nv&cr_hvmem=8192&cr_hvdsk=80&cr_hvcpu=4&cr_hvdskb=1&template=nv.lin.ubuntu2604v1
/vds/update
Adjust HyperVPS VDS or Linux KVM VDS parameters. Typical propagation time is 5 - 10 minutes. VDS will be rebooted to apply if container or disk parameters change, no reboot for metadata parameters such as backup. It is mandatory to specify all new parameters. IMPORTANT NOTE: disk size cannot be decreased - only increased. Be careful not to overshoot, it cannot be undone.
&_key_ - id from /vds/list
All the following parameters are the same as in /vds/create endpoint:
&cr_hvmem
&cr_hvcpu
&cr_hvdsk
&cr_hvdskb
/vds/reboot
Reboot server of all types (including Digital DC and Hardware rent). Typical execution time is 3 - 5 minutes.
&_key_ - id from /vds/list
/vds/online
Internal usage, do not call.
&_key_ - id from /vds/list
&online - 1|0
/vds/delete
Delete server of all types (including Digital DC and Hardware rent).
&_key_ - id from /vds/list
[&force_critical] - 1|0
/vds/ip/list
List IP addresses bound to servers of all types (including Digital DC and Hardware rent).
[&_key_] - id from /vds/list (filter by bound server)
/vds/ip/add
Add new public IP to the server (random IP from the pool). Platform does not manage OS inside server - adjustments to IP configuration are needed in the customer OS. Propagation time to IP filters is 3 - 5 minutes.
&_key_ - id from /vds/list
/vds/ip/delete
Delete the IP from the server. Platform does not manage OS inside server - adjustments to IP configuration are needed in the customer OS. IP is de-assigned instantly and cannot be assigned again - DO NOT delete if the IP is important to keep.
&_key_ - id from /vds/list - owning server
&del_ip - IP address (text form)
/rds/available
Prices and availability status of the dedicated servers (physical servers for rent).
/dds/available
Prices and availability status of the Digital Datacenter servers (corporate VPS).
/email/list
List mailboxes. Includes login, password, mail server addresses, Webmail link.
[&_key_] - id filter (if needed)
/email/add
Create mailbox. Typical creation time is 5 - 10 minutes.
&add_email
/email/delete
Delete mailbox.
&_key_ - id from /email/list
/email/alias/list
List email aliases.
[&_key_] - id filter (if needed)
/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_ - id from /email/alias/list
/website/list
List all Websites and properties, including login / password (if known). It is also recommended to check /overview for descriptive list.
[&_key_] - id filter (if needed)
/website/add
Create new Website and base DNS record in hoster's home domain for instant access. Typical creation time is 3 - 5 minutes.
&name - website name (temp subdomain), keep simple, unique and short (must be whole-hosting unique, reuse forbidden)
&srv_type (avoid Frankfurt if not explicitly 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 depends on server type and can range from 3-5 minutes to 1-2 hours.
&_key_ - id from /website/list
&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_ - id from /website/list
/website/delete
Delete Website.
&_key_ - id from /website/list
/ftp/list
Internal usage, do not call.
/ftp/delete
Internal usage, do not call.
&_key_ - id from /ftp/list
/dns/list
List domains, subdomains, and Website bindings. It is also recommended to check /overview for descriptive list.
[&_key_] - id filter (if needed)
[&_website_] - bound website id filter (if needed)
[&_ip_] - (text form of IP address) - bound server's IP address filter (if needed)
/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] - id from /website/list OR "ip_a.b.c.d" string to bind to server
[&bind_only] - 1|0
/dns/overview
WHOIS, registrar, basic dig / records analysis, prolong / management status description of the domain.
[&_key_] - id from /dns/list, if within the current account
[&domain] - OR - full domain name - the call executes for any domain, including not in the current account
/dns/price
Domain registration / prolong prices and terms. The query is not bound to current account specific situation, it is a generic terms query.
[&domain] - full domain name
/dns/bind
Bind domain name to the Website or to the server, or unbind from the Website or the server. Typical propagation time is 30 - 60 minutes.
&_key_ - id from /dns/list
[&dns_to] - id from /website/list OR "ip_a.b.c.d" string to bind to server, or 0 to unbind.
/dns/delete
Delete domain name.
&_key_ - id from /dns/list
/dns/zone/set-managedmx
Alter the setting that hosting should manage MX record on the domain. Enabling managed MX effects in 1 hour typically. Disabling managed MX should be followed by raw- calls to remove default MX and set desired MX.
&_key_ - id from /dns/list
&upd_managed_mx - 1
&managed_mx - 1|0 - add/keep/update (1) or delete (0) hosting-managed root MX record; deletion of hosting record is not guaranteed - advised to delete manually
/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_ - id from /dns/list
/dns/zone/raw-update
Edit zone file. DO NOT edit records associated with the managed bindings (see /dns/list fields such as website_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_ - id from /dns/list
[&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).
[&_key_] - id filter (if needed)
/database/add
Create new MySQL / Postgres database. Propagation time - instant. Returns id of the new object.
&name - DB name, keep simple, unique and short (must be whole-hosting unique, reuse forbidden)
&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_ - id from /database/list
/database/delete
Delete database.
&_key_ - id from /database/list
/mssql/list
List all Microsoft SQL databases, including login / password (if known).
[&_key_] - id filter (if needed)
/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. | |