User Tools

Site Tools


manuals:vps:api

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
manuals:vps:api [2019/05/17 14:03] – Aithermanuals:vps:api [2026/11/01 19:49] (current) – Add a client overview and complete examples for PHP, Python, JavaScript, TypeScript, Go and Rust aither
Line 1: Line 1:
 +<page>manuals:vps:api</page>
 ====== API ====== ====== API ======
  
Line 8: Line 9:
 ===== API Documentation ===== ===== API Documentation =====
 The API documentation, i.e. a list of objects, possible actions as well as input and output The API documentation, i.e. a list of objects, possible actions as well as input and output
-parameters can be found at https://api.vpsfree.cz/v5.0/.+parameters can be found at https://api.vpsfree.cz/.
  
 Even without logging in, you can see a list of all objects, i.e. even those that only Even without logging in, you can see a list of all objects, i.e. even those that only
Line 16: Line 17:
  
 ===== Working with the API ===== ===== Working with the API =====
-The API is built on the [[https://github.com/vpsfreecz/haveapi|HaveAPI]] framework +The API uses the [[https://github.com/vpsfreecz/haveapi|HaveAPI]] framework. 
-which we have developed. The framework creates +Its [[https://github.com/vpsfreecz/haveapi#what-is-a-self-describing-api|self-description]] 
-a [[https://github.com/vpsfreecz/haveapi#what-is-a-self-describing-api|self-describing]] +lists the available resources, actions and parameters.
-API, which means that premade generic clients can be +
-used:+
  
-  * Ruby - https://github.com/vpsfreecz/vpsfree-client +The following clients are available:
-  * PHP - https://github.com/vpsfreecz/haveapi/tree/master/clients/php +
-  * JavaScript - https://github.com/vpsfreecz/haveapi/tree/master/clients/js +
-  * Go - https://github.com/vpsfreecz/haveapi/tree/master/clients/go +
-  * The HaveAPI web interface - https://github.com/vpsfreecz/haveapi-webui +
-  * A file system based on FUSE - https://github.com/vpsfreecz/haveapi-fs+
  
-Usage examples can always be found in the ''README.md'' of each client. In general, the client +  * [[#installing_vpsfree-client|vpsfreectl CLI]] and [[#ruby_client|Ruby library]] from the ''vpsfree-client'' package 
-receives the API URL, then the client downloads the documentation and uses it for setup.+  * [[#php_client|PHP]] 
 +  * [[#python_client|Python]] 
 +  * [[#dynamic_haveapi_client_for_javascript_and_typescript|Dynamic HaveAPI client for JavaScript and TypeScript]] 
 +  * [[#go_client|Go]] 
 +  * [[#generated_typescript_client_for_vpsadmin|Generated TypeScript client for vpsAdmin]] 
 +  * [[#rust_client|Rust]]
  
 The API is [[wp>Representational state transfer|RESTful]], so any REST client The API is [[wp>Representational state transfer|RESTful]], so any REST client
Line 38: Line 37:
  
 ===== Authentication===== ===== Authentication=====
-There are two authentication methods available. The first and simpler one is HTTP +There are two authentication methods:
-basic. The name and password must be sent along with every API request. This is a good +
-choice for one-off actions. However, if you need to call the API several times or +
-automatically, storing the password on the disk or copying it constantly is not a good idea.+
  
-Another method is authentication using tokens. The way this method works is that +  * [[#http_basic|HTTP Basic]] 
-the client first requests a token to be created, one for which the client needs +  * [[#tokens|Using tokens]] 
-the name, password and possibly TOTP. As soon as the client receives the token, + 
-the name and password can be forgotten since it is the token that is then used +Example usage in different programming languages can be found in [[https://api.vpsfree.cz/|API documentation]]. 
-for further authentication.+ 
 +==== HTTP Basic ==== 
 + The name and password must be sent along with every API request in HTTP header //Authorization//. 
 +This is a good choice for one-off actions. However, if you need to call the API repeatedly or 
 +automatically, storing the password on the disk or entering it constantly is not a good idea. 
 +HTTP Basic cannot be used if two-factor authentication is enabled on your account. 
 + 
 +==== Tokens ==== 
 +The client first requests a token using your credentials and optionally also TOTP. 
 +As soon as the client receives the token, the credentials can be forgotten and the token 
 +is used for authentication.
  
 There can be several types of tokens with different lifetimes: There can be several types of tokens with different lifetimes:
  
-  * fixed - token validity is fixed +  * //fixed// - token validity is fixed 
-  * renewable_manual - token validity can be manually extended +  * //renewable_manual// - token validity can be manually extended 
-  * renewable_auto - token validity is extended after every request +  * //renewable_auto// - token validity is extended after every request 
-  * permament - the token is valid permanently, or until it is deleted+  * //permanent// - the token is valid permanently, or until it is deleted
  
 The type of token and time period by which its validity is extended is chosen The type of token and time period by which its validity is extended is chosen
 by the client. by the client.
  
-===== CLI ===== +Token authentication must be enabled for your account. The examples below show 
-[[https://github.com/vpsfreecz/vpsfree-client|The Ruby client]] also includes a CLI. +login with username and password. If your account also requires a TOTP code or 
-In order for it to work properly, you need Ruby >= 2.0 and Ruby header files, +a password change, use the client's documented login flow or an existing token.
-OpenSSL and ncurses (mostly packages with the ''-dev'' or ''-devel'' suffix)+
  
-<note> +===== Scopes ===== 
-If you’re using OS X, you first need to install OpenSSL using [[http://brew.sh/|Homebrew]] and only then +Authentication tokens can be restricted to selected actions. Each action has its own scope, 
-can you install EventMachine (a gem required by the client).+you can find the available scopes in the documentation. You can configure scopes when you're 
 +requesting a new authentication token.
  
-<code> +Example scopes:
-$ brew install openssl +
-$ sudo gem install eventmachine -- --with-opt-include="/usr/local/opt/openssl/" +
-</code> +
-</note>+
  
-It can be installed using ruby gems:+  * ''all'' allow access to all actions, this is used by the web interface and it is the default scope 
 +  *  an empty scope will allow access only to ''user#current'', which gives information about the current user; this is used for logins from Discourse and KB 
 +  * ''vps#show'' allow access to action show on vps resource 
 +  * ''vps#show:vps_id=123'' allow access to action show on a specific VPS 
 +  * ''vps#*'' allow all actions on vps resource 
 +  * ''vps#*:vps_id=123'' all actions on vps resource, but only with VPS ID 123 
 +  * ''{vps,dataset}#{index,show}'' list and show info about VPS and datasets
  
-<code> +Scopes can contain globs for resource and action names. Action name is separated from resource name by a hash (''#''). Optional object IDs are separated from action name by a colon ('':'') and cannot contain globs. You can find a list of available scopes and their parameters in the [[https://api.vpsfree.cz/|documentation]]. Each token can have multiple scopes separated by spaces. At least one scope must match the called action in order for access to be granted.
-$ gem install vpsfree-client +
-</code>+
  
-==== Installing in Windows 10 Using a Ubuntu Linux Subsystem ==== +===== Installing vpsfree-client ===== 
- +The [[https://github.com/vpsfreecz/vpsfree-client|vpsfree-client]] package includes 
-=== Installing Ubuntu (Windows 10 Subsystem for Linux) === +the ''vpsfreectl'' command-line tool and a library for Ruby scripts. 
- +You need Ruby, Ruby header files and ncurses (usually packages with the ''-dev'' 
-  - in Windows 10, enable Developer Mode, let it install +or ''-devel'' suffix). See the [[https://rubygems.org/gems/vpsfree-client|package page]] 
-  - in the Programs and Features menu, open Turn Windows Features On or Off, scroll to the very bottom, choose Windows Subsystem for Linux, run the installation and let the computer restart +for dependency requirements.
-  - after the restart, run bash in the Start menu as admin +
-  - create a Unix username and password +
-  - press the Y key and let the Ubuntu base be installed +
- +
-=== Installing Dependencies ===+
  
 <code bash> <code bash>
-sudo apt-get install ruby2.0 ruby2.0-dev libssl-dev make g+++gem install vpsfree-client
 </code> </code>
  
-=== A Quick & Dirty Fix to Set Ruby2.0 as Default Instead of 1.9 === +Platform-specific instructions:
- +
-<code bash> +
-sudo rm /usr/bin/ruby /usr/bin/gem /usr/bin/irb /usr/bin/rdoc /usr/bin/erb +
-sudo ln -s /usr/bin/ruby2.0 /usr/bin/ruby +
-sudo ln -s /usr/bin/gem2.0 /usr/bin/gem +
-sudo ln -s /usr/bin/irb2.0 /usr/bin/irb +
-sudo ln -s /usr/bin/rdoc2.0 /usr/bin/rdoc +
-sudo ln -s /usr/bin/erb2.0 /usr/bin/erb +
-sudo gem update --system +
-sudo gem pristine --all +
-</code> +
- +
-Source: http://blog.costan.us/2014/04/restoring-ruby-20-on-ubuntu-1404.html +
- +
-=== Installing vpsfree-client === +
- +
-<code bash> +
-sudo gem install vpsfree-client +
-</code> +
- +
- +
-----+
  
 +  * [[manuals:vps:api:macos|macOS]]
 +  * [[manuals:vps:api:windows|Windows]]
  
-After the installation,  ''vpsfreectl'' should be available in ''$PATH''. If not,+After the installation, ''vpsfreectl'' should be available in ''$PATH''. If not,
 this can be fixed easily: this can be fixed easily:
  
Line 132: Line 113:
  
 <code> <code>
-$ PATH="$PATH:/home/user/.gem/ruby/2.0.0/bin"+$ export PATH="$PATH:$(ruby -r rubygems -e 'puts Gem.bindir')"
 </code> </code>
  
-==== Usage ====+===== Using CLI =====
  
 <code> <code>
Line 288: Line 269:
         --user USER                  User name         --user USER                  User name
         --password PASSWORD          Password         --password PASSWORD          Password
 +        --scope [SCOPE]              Scope
         --token TOKEN                Token         --token TOKEN                Token
         --token-lifetime LIFETIME    Token lifetime, defaults to renewable_auto         --token-lifetime LIFETIME    Token lifetime, defaults to renewable_auto
Line 332: Line 314:
 access to ''~/.haveapi-client.yml'' can access and use the token. access to ''~/.haveapi-client.yml'' can access and use the token.
 </note> </note>
 +
 +Specify a scope:
 +
 +<code>
 +$ vpsfreectl --auth token --scope 'vps#*:vps_id=123' --save vps show 123
 +</code>
 +
 +The command above will ask for an authentication token that will only be allowed to call actions on the vps resource and only on VPS with ID 123.
  
 ==== Actions and Parameters ==== ==== Actions and Parameters ====
Line 507: Line 497:
 </code> </code>
  
-===== File system ====== +===== Ruby client =====
-''haveapi-fs'' is a file system based on FUSE, i.e. it makes it possible to mount +
-the API as a file system from userspace. Objects, actions and their parameters can be +
-browsed like folders and files in any program. The file system is installed the same way +
-as a CLI, it just has a different name:+
  
-<code> +Use the library from the same ''vpsfree-client'' package in your own scripts. 
-$ gem install haveapi-fs +The example requests an [[#tokens|API token]] with your vpsAdmin username and 
-</code>+password, then lists your VPSes. Replace ''USERNAME'' and ''PASSWORD'' with your 
 +credentials. To use an existing token, replace the login code with the commented 
 +alternative and fill in ''TOKEN'':
  
-==== Usage ==== +<code ruby> 
-The usage of ''haveapi-fs'' is described in detail in +require 'vpsfree/client'
-[[https://github.com/vpsfreecz/haveapi-fs#usage|README.md]]. This is just a +
-brief description.+
  
-<code> +api = VpsFree::Client.new 
-$ haveapi-fs https://api.vpsfree.cz /mnt/api.vpsfree.cz +api.authenticate(:token, user: 'USERNAME', password: 'PASSWORD', 
-Username: mylogin +                 lifetime: 'renewable_auto') 
-Password:+# Or replace the login call above with an existing token: 
 +# api.authenticate(:token, token: 'TOKEN')
  
-$ cd /mnt/api.vpsfree.cz +api.vps.list.each do |vps| 
-$ ls -1 +  puts "#{vps.id}: #{vps.hostname}" 
-auth_token +end
-cluster +
-cluster_resource +
-dataset +
-dataset_plan +
-dns_resolver +
-environment +
-help.html +
-help.man +
-help.md +
-help.txt +
-ip_address +
-language +
-location +
-mail_template +
-migration_plan +
-node +
-object_history +
-os_template +
-snapshot_download +
-transaction +
-transaction_chain +
-user +
-user_session +
-vps +
-vps_config+
 </code> </code>
  
-Each folder contains the files ''help.{html,txt,md,man}'', which describe what +See the [[https://github.com/vpsfreecz/vpsfree-client#client-library|client README]] 
-the current folder contains. +for more library examples.
- +
-<code> +
-$ cat vps/5685/hostname  +
-my-vps  +
- +
-$ echo better-hostname > vps/5685/hostname  +
-$ echo 1 > vps/5685/save +
-$ cat vps/5685/actions/update/status  +
-1 +
-$ cat vps/5685/hostname +
-better-hostname  +
-</code> +
- +
-The example demonstrates that individual object attributes can simply be changed by +
-writing into a file. The save action can be called by writing a one, or it can +
-be run as an executable file. +
- +
-In order to get clearer creation/modification of objects, you can use the YAML files +
-''create.yml'' or ''update.yml''. These files contain parameters in the form of +
-a hash and after saving and closing the file, the corresponding action is performed. +
- +
-This way, you can perform any operation in the API.+
  
-===== Usage Examples =====+==== Usage Examples ====
 The following scripts demonstrate ways you can use the API. These scripts can be The following scripts demonstrate ways you can use the API. These scripts can be
 run from anywhere – manually, from cron, etc. run from anywhere – manually, from cron, etc.
Line 592: Line 532:
 </note> </note>
  
-==== Daily Downloads of VPS Backups ====+=== Daily Downloads of VPS Backups ===
 <code> <code>
 #!/usr/bin/env ruby #!/usr/bin/env ruby
Line 599: Line 539:
  
 api = VpsFree::Client.new api = VpsFree::Client.new
-api.authenticate(:token, token: 'PUT YOUR TOKEN HERE')+api.authenticate(:token, user: 'USERNAME', password: 'PASSWORD', 
 +                 lifetime: 'renewable_auto') 
 +# Or replace the login call above with an existing token: 
 +# api.authenticate(:token, token: 'TOKEN')
  
 api.dataset.list(role: :hypervisor).each do |ds| api.dataset.list(role: :hypervisor).each do |ds|
Line 623: Line 566:
 </code> </code>
  
-==== Daily NAS Backups with a Weekly History ====+=== Daily NAS Backups with a Weekly History ===
 <code> <code>
 #!/usr/bin/env ruby #!/usr/bin/env ruby
Line 630: Line 573:
  
 api = VpsFree::Client.new api = VpsFree::Client.new
-api.authenticate(:token, token: 'PUT YOUR TOKEN HERE')+api.authenticate(:token, user: 'USERNAME', password: 'PASSWORD', 
 +                 lifetime: 'renewable_auto') 
 +# Or replace the login call above with an existing token: 
 +# api.authenticate(:token, token: 'TOKEN')
  
 api.dataset.list(role: :primary).each do |ds| api.dataset.list(role: :primary).each do |ds|
Line 654: Line 600:
 end end
 </code> </code>
 +
 +===== Other clients =====
 +
 +Each example requests an [[#tokens|API token]] with your vpsAdmin username and
 +password, then prints the ID and hostname of up to 10 VPSes. Replace ''USERNAME''
 +and ''PASSWORD'' with your credentials. To use an existing token, replace the
 +login code with the commented alternative and fill in ''TOKEN''.
 +
 +==== PHP client ====
 +
 +Install the [[https://github.com/vpsfreecz/haveapi/tree/master/clients/php|HaveAPI PHP client]]
 +using Composer:
 +
 +<code bash>
 +composer require haveapi/client
 +</code>
 +
 +Save this example as ''vps-list.php'' next to the ''vendor'' directory and run it
 +with ''php vps-list.php'':
 +
 +<code php>
 +<?php
 +require __DIR__ . '/vendor/autoload.php';
 +
 +$api = new \HaveAPI\Client('https://api.vpsfree.cz');
 +$api->authenticate('token', ['user' => 'USERNAME', 'password' => 'PASSWORD']);
 +// Or replace the login call above with an existing token:
 +// $api->authenticate('token', ['token' => 'TOKEN']);
 +
 +foreach ($api->vps->list(['limit' => 10]) as $vps) {
 +    echo $vps->id . ': ' . $vps->hostname . PHP_EOL;
 +}
 +</code>
 +
 +See the [[https://github.com/vpsfreecz/haveapi/tree/master/clients/php#usage|client README]]
 +for other actions and error handling.
 +
 +==== Python client ====
 +
 +Install [[https://pypi.org/project/haveapi-client/|haveapi-client]] using pip:
 +
 +<code bash>
 +python -m pip install haveapi-client
 +</code>
 +
 +Save this example as ''vps-list.py'' and run it with ''python vps-list.py'':
 +
 +<code python>
 +from haveapi_client import Authenticated, Client, TokenAuth
 +
 +with Client("https://api.vpsfree.cz") as api:
 +    login = api.begin_token_login({
 +        "user": "USERNAME",
 +        "password": "PASSWORD",
 +        "lifetime": "renewable_auto",
 +    })
 +    if not isinstance(login, Authenticated):
 +        raise RuntimeError("Login requires another step")
 +    # Or replace the login block above with an existing token:
 +    # api.set_auth(TokenAuth("TOKEN"))
 +
 +    result = api.vps.list(limit=10)
 +    for vps in result.data:
 +        print(vps["id"], vps["hostname"])
 +</code>
 +
 +The [[https://github.com/vpsfreecz/haveapi/tree/master/clients/python|client README]]
 +also covers asynchronous calls with ''AsyncClient''.
 +
 +==== Dynamic HaveAPI client for JavaScript and TypeScript ====
 +
 +Both languages use the same npm package, which includes TypeScript declarations:
 +
 +<code bash>
 +npm install haveapi-client
 +</code>
 +
 +This example works in JavaScript and TypeScript. To run it with Node.js, save it
 +as ''vps-list.mjs'' and use ''node vps-list.mjs'':
 +
 +<code javascript>
 +import { AsyncClient } from "haveapi-client";
 +
 +async function main() {
 +  const api = new AsyncClient("https://api.vpsfree.cz");
 +  await api.authenticate("token", { user: "USERNAME", password: "PASSWORD" });
 +  // Or replace the login call above with an existing token:
 +  // await api.authenticate("token", { token: "TOKEN" });
 +  const result = await api.resource("vps").action("list")({
 +    params: { limit: 10 },
 +  });
 +  const vpses = result.response.data;
 +  if (Array.isArray(vpses)) {
 +    for (const vps of vpses) {
 +      console.log(vps.id, vps.hostname);
 +    }
 +  }
 +}
 +
 +main().catch(() => console.error("The API request failed."));
 +</code>
 +
 +See the [[https://github.com/vpsfreecz/haveapi/tree/master/clients/js|client README]]
 +for other actions and browser usage.
 +
 +==== Go client ====
 +
 +Add the [[https://github.com/vpsfreecz/vpsadmin-go-client|vpsAdmin Go client]]
 +to your Go module:
 +
 +<code bash>
 +go get github.com/vpsfreecz/vpsadmin-go-client/client
 +</code>
 +
 +Save this example as ''main.go'' and run it with ''go run .'':
 +
 +<code go>
 +package main
 +
 +import (
 + "fmt"
 + "log"
 +
 + "github.com/vpsfreecz/vpsadmin-go-client/client"
 +)
 +
 +func main() {
 + api := client.New("https://api.vpsfree.cz")
 + if err := api.SetNewTokenAuth(&client.TokenAuthOptions{
 + User:     "USERNAME",
 + Password: "PASSWORD",
 + }); err != nil {
 + log.Fatal(err)
 + }
 + // Or replace the login block above with an existing token:
 + // api.SetExistingTokenAuth("TOKEN")
 +
 + action := api.Vps.Index.Prepare()
 + action.NewInput().SetLimit(10)
 + response, err := action.Call()
 + if err != nil {
 + log.Fatal(err)
 + }
 + if !response.Status {
 + log.Fatalf("%s: %v", response.Message, response.Errors)
 + }
 +
 + for _, vps := range response.Output {
 + fmt.Println(vps.Id, vps.Hostname)
 + }
 +}
 +</code>
 +
 +See the [[https://github.com/vpsfreecz/vpsadmin-go-client#usage|client README]]
 +for other actions and parameters.
 +
 +==== Generated TypeScript client for vpsAdmin ====
 +
 +The [[https://github.com/vpsfreecz/vpsadmin-typescript-client|vpsAdmin TypeScript client]]
 +provides typed methods for vpsAdmin resources and actions. Install it using npm,
 +which also installs its ''haveapi-client'' dependency:
 +
 +<code bash>
 +npm install vpsadmin-typescript-client
 +</code>
 +
 +This example works in JavaScript and TypeScript. To run it with Node.js, save it
 +as ''vps-list.mjs'' and use ''node vps-list.mjs''.
 +Use ''https://api.vpsfree.cz/v7.0'' as the base URL for this client:
 +
 +<code javascript>
 +import { AsyncClient } from "haveapi-client";
 +import { createHaveApiExecutor, createVpsAdminClient } from "vpsadmin-typescript-client";
 +
 +async function main() {
 +  const runtime = new AsyncClient("https://api.vpsfree.cz/v7.0");
 +  await runtime.authenticate("token", { user: "USERNAME", password: "PASSWORD" });
 +  // Or replace the login call above with an existing token:
 +  // await runtime.authenticate("token", { token: "TOKEN" });
 +  const api = createVpsAdminClient({ execute: createHaveApiExecutor(runtime) });
 +  const page = await api.vps.index({ params: { limit: 10 } });
 +  for (const vps of page.data) {
 +    console.log(vps.id, vps.hostname);
 +  }
 +}
 +
 +main().catch(() => console.error("The API request failed."));
 +</code>
 +
 +See the [[https://github.com/vpsfreecz/vpsadmin-typescript-client#readme|client README]]
 +for other actions and types.
 +
 +==== Rust client ====
 +
 +Add the [[https://crates.io/crates/vpsadmin-client|vpsadmin-client]] crate to your
 +Rust project. This example uses synchronous calls, so enable the ''blocking'' feature:
 +
 +<code bash>
 +cargo add vpsadmin-client --features blocking
 +</code>
 +
 +Save this example as ''src/main.rs'' and run it with ''cargo run'':
 +
 +<code rust>
 +use vpsadmin_client::{blocking::Client, TokenStep};
 +
 +fn main() -> Result<(), Box<dyn std::error::Error>> {
 +    let login = Client::builder("https://api.vpsfree.cz").build()?;
 +    let response = login.authentication__token__token().request()
 +        .user("USERNAME")
 +        .password("PASSWORD")
 +        .lifetime("renewable_auto")
 +        .send()?;
 +    let TokenStep::Complete { token } = response.output.token_step()? else {
 +        return Err("Login requires another step".into());
 +    };
 +    let api = Client::builder("https://api.vpsfree.cz")
 +        .token(token.expose_secret())
 +        .build()?;
 +    // Or replace the login and client setup above with an existing token:
 +    // let api = Client::builder("https://api.vpsfree.cz").token("TOKEN").build()?;
 +
 +    let response = api.vps().index().limit(10).send()?;
 +    for vps in response.output {
 +        if let (Some(id), Some(hostname)) = (vps.id, vps.hostname) {
 +            println!("{} {}", id, hostname);
 +        }
 +    }
 +    Ok(())
 +}
 +</code>
 +
 +See the [[https://github.com/vpsfreecz/vpsadmin-rust-client#readme|client README]]
 +for other actions, asynchronous calls and Rust requirements.
 +
  
manuals/vps/api.1558101791.txt.gz · Last modified: by Aither