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 [2025/03/24 20:40] – Fix API doc link 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 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 (outdated) +
-  * A file system based on FUSE - https://github.com/vpsfreecz/haveapi-fs (outdated)+
  
-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 43: Line 42:
   * [[#tokens|Using tokens]]   * [[#tokens|Using tokens]]
  
-Example usage in different programming languages can be found in [[https://api.vpsfree.cz/v6.0/#auth|API documentation]].+Example usage in different programming languages can be found in [[https://api.vpsfree.cz/|API documentation]].
  
 ==== HTTP Basic ==== ==== HTTP Basic ====
Line 61: Line 60:
   * //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.
 +
 +Token authentication must be enabled for your account. The examples below show
 +login with username and password. If your account also requires a TOTP code or
 +a password change, use the client's documented login flow or an existing token.
  
 ===== Scopes ===== ===== Scopes =====
Line 84: Line 87:
  
 ===== Installing vpsfree-client ===== ===== Installing vpsfree-client =====
-[[https://github.com/vpsfreecz/vpsfree-client|The Ruby client]] also includes a CLI. +The [[https://github.com/vpsfreecz/vpsfree-client|vpsfree-client]] package includes 
-In order for it to work properly, you need Ruby >= 2.7, Ruby header files and ncurses (mostly packages with the ''-dev'' or ''-devel'' suffix).+the ''vpsfreectl'' command-line tool and a library for Ruby scripts. 
 +You need Ruby, Ruby header files and ncurses (usually packages with the ''-dev'' 
 +or ''-devel'' suffix). See the [[https://rubygems.org/gems/vpsfree-client|package page]] 
 +for dependency requirements.
  
 <code bash> <code bash>
Line 107: Line 113:
  
 <code> <code>
-$ PATH="$PATH:/home/user/.gem/ruby/3.0.0/bin"+$ export PATH="$PATH:$(ruby -r rubygems -e 'puts Gem.bindir')"
 </code> </code>
  
-==== Using CLI ====+===== Using CLI =====
  
 <code> <code>
Line 491: 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 576: 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 583: 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 607: 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 614: 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 638: 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.1742848818.txt.gz · Last modified: by aither