API - Other Languages

Details of how to use the AMP API can be found in the Blockstream AMP API Tutorial. The main tutorial is in Python but you can use the language examples below as a template to call all endpoints in the language of your choice.

import requests
import json

# TESTNET
API_URL='https://amp-test.blockstream.com/api'

username = 'your_amp_username'
password = 'your_amp_password'

url = f'{API_URL}/user/obtain_token'
headers = {'content-type': 'application/json'}
payload = {'username': username, 'password': password}
response = requests.post(url, data=json.dumps(payload), headers=headers)
assert response.status_code == 200
json_data = json.loads(response.text)
token = json_data['token']
print(token)
# You can now use the header for any AMP API calls:
header = {'content-type': 'application/json', 'Authorization': f'token {token}'}
print(header)

url = f'{API_URL}/assets/'
response = requests.get(url, headers=header)
assert response.status_code == 200
assets = json.loads(response.text)
print(assets)
const request = require('request');

let username = "your_amp_username";
let password = "your_amp_password";

data = { "username": username, "password": password }

options = {
    url: "https://amp-test.blockstream.com/api/user/obtain_token",
    method: "post",
    headers:
    {
     "Content-Type": "application/json"
    },
    body: JSON.stringify( data )
};

request(options, (error, response, body) => {
    if (error) {
        console.error('An error occurred: ', error);
    } else {
        json = JSON.parse(body);
        token = json.token;
        console.log(token);
        // Use the authorization token to call an endpoint requiring authorization
        let options = {
            url: `https://amp-test.blockstream.com/api/assets/`,
            method: "get",
            headers:
            {
             "Content-Type": "application/json",
             "Authorization": `token ${token}`
            }
        };
        request(options, (error, response, body) => {
            if (error) {
                console.error('An error occurred: ', error);
            } else {
                json = JSON.parse(body);
                console.log(json);
            }
        });
    };
});
require 'net/http'
require 'uri'
require 'json'

uri = URI('https://amp-test.blockstream.com/api/user/obtain_token')

username = 'your_amp_pGreen_QA_TEST_2'
password = 'R9nc63yTBv3y8msQ'

token = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
  request = Net::HTTP::Post.new(uri, initheader = {'Content-Type' => 'application/json'})
  request.body = {username: "#{username}", password: "#{password}"}.to_json
  response = http.request request
  obj = JSON.parse(response.body)
  obj['token']
end
puts token

# Then use the token to call an endpoint requiring authorization here
# and using headers like this:
uri = URI('https://amp-test.blockstream.com/api/assets/')
req = Net::HTTP::Get.new(uri)
req['Content-Type'] = "application/json"
req['Authorization'] = "token #{token}"

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http|
  http.request(req)
}
puts res.body
using System;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace dotnetamp
{
    // Example classes to enable Serialization and Deserialization. This is
    // not required but may help you use the data returned in your code:
    public class ObtainTokenRequest
    {
        public string username { get; set; }
        public string password { get; set; }
    }

    public class ObtainTokenResponse
    {
        public string token { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            // Initialize the HttpClient object with AMP test instance URL.
            HttpClient _client = new HttpClient { BaseAddress = new Uri("https://amp-test.blockstream.com/api/") };

            // An HTTP GET call that does not need Authorization:
            var result = await _client.GetAsync("info");

            // Get the result as a JSON string:
            var jsonResult = await result.Content.ReadAsStringAsync();
            Console.WriteLine(jsonResult);

            // To call endpoints that need authorization we first need to obtain an
            // Authorization token using the AMP account's username and password.
            // This also shows how to serialize and deserialize a request and
            // response, although that is not required, it can be useful.
            var tokenRequest = new ObtainTokenRequest()
            {
                username = "your_amp_username",
                password = "your_amp_password",
            };

            // Serialize the object and get the content as a JSON string to pass to the API:
            var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(tokenRequest);
            Console.WriteLine(jsonRequest);
            var content = new StringContent(jsonRequest, Encoding.Default, "application/json");

            // Make an HTTP POST call that to obtain the Authorization token:
            result = await _client.PostAsync("user/obtain_token", content);
            jsonResult = await result.Content.ReadAsStringAsync();

            string token = "";

            if (!result.IsSuccessStatusCode)
            {
                Console.WriteLine("FAILED TO GET TOKEN");
            }
            else
            {
                // Deserialize into an ObtainTokenResponse object:
                ObtainTokenResponse obtainTokenResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ObtainTokenResponse>(jsonResult);
                token = obtainTokenResponse.token;
                Console.WriteLine(token);
            }

            // Most calls require the use of the Authorization token obtained above
            // It must be set as the Authorization token header:
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", token);

            // NOTE: Using HttpClient, if you do not include the trailing / for calls to API that have
            // possilbe further paths e.g. /assets/{assetUuid} the call returns an authorization error.
            // Now we can make a call to an endpoint that requires authorization:
            result = await _client.GetAsync("assets/");

            // Here we will not Deserialize the result, just get it as a JSON string:
            jsonResult = await result.Content.ReadAsStringAsync();
            Console.WriteLine(jsonResult);

            // Once set, the Authorization header need not be set again within this conext and the
            // client will use it for subsequent calls:
            result = await _client.GetAsync("registered_users/");
            jsonResult = await result.Content.ReadAsStringAsync();
            Console.WriteLine(jsonResult);
        }
    }
}
package main

import (
    "log"
    "net/http"
    "encoding/json"
    "bytes"
    "io/ioutil"
    "fmt"
)

type Obtain_Token struct {
    Token string `json:"token"`
}

type Asset struct {
    Name string
}

func main() {
    log.SetFlags(0)
    
    url := "https://amp-test.blockstream.com/api/user/obtain_token"
    client := http.Client{}
    req , err := http.NewRequest("GET", url, nil)

    var jsonData = []byte(`{
        "username": "your_amp_username",
        "password": "your_amp_password"
    }`)

    req , err = http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header = http.Header{
        "Content-Type": []string{"application/json"},
    }

    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }

    defer resp.Body.Close()
    
    ot := new(Obtain_Token)
    
    if err := json.NewDecoder(resp.Body).Decode(ot); err != nil {
        log.Fatalln(err)
    }

    log.Println(ot.Token)
    
    url = "https://amp-test.blockstream.com/api/assets/"

    req , err = http.NewRequest("GET", url, nil)

    if err != nil {
        log.Fatalln(err)
    }

    req.Header = http.Header{
        "Content-Type": []string{"application/json"},
        "Authorization": []string{"token " + ot.Token},
    }

    resp, err = client.Do(req)

    if err != nil {
        log.Fatalln(err)
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        log.Fatal(err)
    }

    var asset []Asset
    err = json.Unmarshal(body, &asset)
    fmt.Printf("%v\n", asset)
}

The Liquid Network is a Bitcoin layer-2 enabling the issuance of security tokens and other digital assets.

© 2023 Liquid Network
All rights reserved.

Feedback and Content Requests

We'd be happy to hear your suggestions on how we can improve this site.

BuildOnL2 Community

The official BuildOnL2 community lives
at community.liquid.net. Join us and build the future of Bitcoin on Liquid.

Telegram

Community-driven telegram group where
most of the Liquid developers hang out.
Go to t.me/liquid_devel to join.