Blockstream AMP API - Other Language Examples¶
The following examples can be used as templates when converting the main tutorial’s Python examples.
An example in Ruby¶
You can check if Ruby is installed on your operating system, and install it if not, by following the Ruby installation steps.
Create a new file named ruby-example.rb and paste the code below into it:
# Tested for: ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-gnu]
require 'net/http'
require 'uri'
require 'json'
# 1. Perform a GET where no authorization token is needed
uri = URI.parse("https://amp-test.blockstream.com/api/info")
req = Net::HTTP::Get.new(uri)
req['Content-Type'] = "application/json"
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http|
http.request(req)
}
puts res.body if res.is_a?(Net::HTTPSuccess)
# 2. Perform a GET where an authorization token is needed
# First use your AMP username and password to obtain your authorization token:
uri = URI('https://amp-test.blockstream.com/api/user/obtain_token')
username = 'your_amp_account_username_here'
password = 'your_amp_account_password_here'
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
# Then use the authorization token to call an endpoint requiring authorization
# We will be using the GAID/AMP ID validation endpoint
valid_testnet_amp_id = 'GADDuLqR8hWYwcFrxNey48bdBatj2'
uri = URI.parse("https://amp-test.blockstream.com/api/gaids/#{valid_testnet_amp_id}/validate")
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)
}
is_valid = JSON.parse(res.body)['is_valid']
puts "AMP ID #{valid_testnet_amp_id} is valid: #{is_valid}"
Execute the code from the command line:
ruby ruby-example.rb
The output will obtain an authorization token using your AMP account’s username and password and use the token to call an endpoint that requires authorization, validating a Green wallet GAID/AMP ID, and printing the result.
An example in C# (.NET)¶
The following can be run from within a code editor, such as Visual Studio Code, or can be compiled and executed.
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_account_username_here",
password = "your_amp_account_password_here",
};
// 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);
}
}
}
Run the file from the editor or from the command line and the example will obtain an authorization token using your AMP account’s username and password and use the token to call an endpoint that requires authorization.
An example in Node.js¶
Create a project directory for the Node.js example and move into it:
mkdir ampnodejs
cd ampnodejs
Generate package.json and install the request package:
npm init --yes
npm install request --save
Create a new file named nodejs-example.js and paste the code below into it:
const request = require('request');
// 1. Perform a GET where no authorization token is needed
let options = {
url: "https://amp-test.blockstream.com/api/info",
method: "get",
headers:
{
"content-type": "application/json"
}
};
request(options, (error, response, body) => {
if (error) {
console.error('An error occurred: ', error);
} else {
json = JSON.parse(body);
console.log(json.version);
}
});
// 1. Perform a GET where an authorization token is needed
// Use your AMP username and password to obtain your authorization token:
let username = "your_amp_account_username_here";
let password = "your_amp_account_password_here";
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
// We will be using the GAID/AMP ID validation endpoint
valid_testnet_amp_id = 'GADDuLqR8hWYwcFrxNey48bdBatj2';
let options = {
url: `https://amp-test.blockstream.com/api/gaids/${valid_testnet_amp_id}/validate`,
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(`AMP ID ${valid_testnet_amp_id} is valid: ${json.is_valid}`);
}
});
};
});
Run the code from the command line:
node nodejs-example.js
The output will obtain an authorization token using your AMP account’s username and password and use the token to call an endpoint that requires authorization, validating a Green wallet GAID/AMP ID, and printing the result.
An example in Go¶
Create a directory for the Go example and move into it:
mkdir src
cd src
mkdir go-example
cd go-example
With the go-example directory create a file named go-example.go and paste the following into it:
package main
import (
"log"
"net/http"
"encoding/json"
"bytes"
"strconv"
)
type Info struct {
Version string `json:"version"`
Notes string `json:"notes"`
}
type Obtain_Token struct {
Token string `json:"token"`
}
type Validate_GAID struct {
Is_Valid bool `json:"is_valid"`
Error string `json:"error"`
}
func main() {
log.SetFlags(0)
// 1. Perform a GET where no authorization token is needed
url := "https://amp-test.blockstream.com/api/info"
client := http.Client{}
req , err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatalln(err)
}
req.Header = http.Header{
"Content-Type": []string{"application/json"},
}
resp , err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
if err != nil {
log.Fatalln(err)
}
i := new(Info)
if err := json.NewDecoder(resp.Body).Decode(i); err != nil {
log.Fatalln(err)
}
log.Println(i.Version)
// 1. Perform a GET where an authorization token is needed
// Use your AMP username and password to obtain your authorization token:
url = "https://amp-test.blockstream.com/api/user/obtain_token"
var jsonData = []byte(`{
"username": "your_amp_account_username_here",
"password": "your_amp_account_password_here"
}`)
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 {
log.Fatalln(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)
// Use the authorization token to call an endpoint requiring authorization
// We will be using the GAID/AMP ID validation endpoint
gaid := "GADDuLqR8hWYwcFrxNey48bdBatj2"
url = "https://amp-test.blockstream.com/api/gaids/" + gaid + "/validate"
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 c2a362f2b6ade0c4676d155d61804aba4059d0ff"},
}
resp, err = client.Do(req)
if err != nil {
log.Fatalln(err)
}
g := new(Validate_GAID)
if err := json.NewDecoder(resp.Body).Decode(g); err != nil {
log.Fatalln(err)
}
log.Println("AMP ID " + gaid + " is valid: " + strconv.FormatBool(g.Is_Valid))
}
Compile and run the code from the command line:
go build
./go-example
The output will obtain an authorization token using your AMP account’s username and password and use the token to call an endpoint that requires authorization, validating a Green wallet GAID/AMP ID, and printing the result.