A Bitcoin-Payable API

Posted by David Harding, Saïvann Carignan

A Bitcoin-Payable API

Overview

In this tutorial we'll show you how to build and host a simple bitcoin-payable API server. In this example, we will convert text to speech, but you can easily extend it to sell many different kinds of API calls.

Prerequisites

Install 21

You will need the following items:

If you've got all the prerequisites, you are ready to go. Let's get started!

Step 1: Create the micropayments server

Open up a new terminal window. If you use a 21 Bitcoin Computer, ssh into it:

## Only necessary if you use a 21 Bitcoin Computer
ssh twenty@IP_ADDRESS

Install the eSpeak TTS engine, create a project directory, and the Flask library for Python 3.

## If you use Linux
sudo apt-get -y install espeak
## If you use Mac OS X
brew install portaudio espeak
## For both Linux and Mac
pip3 install flask
mkdir tts-402-server

Within this directory, create a file called bitcoin-api-server.py and type in the following code:

#!/usr/bin/env python3
from subprocess import call
from uuid import uuid4

from flask import Flask
from flask import request
from flask import send_from_directory

from two1.wallet import Wallet
from two1.bitserv.flask import Payment

# Configure the app and wallet
app = Flask(__name__)
wallet = Wallet()
payment = Payment(app, wallet)


# Charge a fixed fee of 3000 satoshis per request to the
# /tts endpoint
@app.route('/tts')
@payment.required(3000)
def tts():
    # the text the client sent us
    text = str(request.args.get('text'))

    # a file to store the rendered audio file
    file = str(uuid4()) + '.wav'

    # run the TTS engine
    call(['espeak', '-w', '/tmp/' + file, text])

    # send the rendered audio back to the client
    return send_from_directory(
        '/tmp',
        file,
        as_attachment=True
    )

# Initialize and run the server
if __name__ == '__main__':
    app.run(host='::')

Save and close the file, and then run the following command:

python3 tts-402-server/bitcoin-api-server.py

Step 2: Create a client to purchase the service

Leave the previous terminal running and open a new terminal. If you have a 21 Bitcoin Computer, ssh into it:

## Only necessary if you use a 21 Bitcoin Computer
ssh twenty@IP_ADDRESS

Create a folder to house the client project:

mkdir tts-402-client

Within this directory, open a file called bitcoin-api-client.py in a text editor and type in the following code:

#!/usr/bin/env python3

from two1.wallet import Wallet
from two1.bitrequests import BitTransferRequests

# Configure your Bitcoin wallet.
wallet = Wallet()
requests = BitTransferRequests(wallet)

SERVER_IP_ADDRESS = '[::1]'


# Send text to the endpoint
def send_text(text):
    # tell the user what text they're sending
    print('You sent {0}'.format(text))

    # 402 endpoint URL and request
    tts_url = 'http://' + SERVER_IP_ADDRESS + ':5000/tts?text={0}'
    speech = requests.get(url=tts_url.format(text))

    if speech.status_code != 200:
        raise Exception('Server produced a %d error' % speech.status_code)

    # save the received audio file to disk
    speech_output = open('speech.wav', 'wb')
    speech_output.write(speech.content)
    speech_output.close()

# Read the text to speechify from the CLI
if __name__ == '__main__':
    from sys import argv
    send_text(argv[1])

Once you're done editing, save the file, exit your text editor, and run:

python3 tts-402-client/bitcoin-api-client.py "hello world"

This should print a line with your phrase, contact the API server, pay the conversion fee using one of the 21 micropayments methods, convert your text to speech, send the client the file, and then save the file in the current directory as speech.wav.

You can now play this file in any media player.

Next Steps

You've learned how to build a very simple API server in which someone can send a text and get back an audio transcription of that text. Here are some ideas on what to build next:

If you build anything like this and want to earn some bitcoin for your efforts, write it up and submit it as a bitcoin tutorial. If we decide to publish it on our site, you'll win $200 in BTC!

You can also come to our Slack channel at slack.21.co to find other 21 users to play your game and give feedback. We look forward to seeing you there!


How to send your Bitcoin to the Blockchain

Just as a reminder, you can send bitcoin mined or earned in your 21.co balance to the blockchain at any time by running 21 flush . A transaction will be created within 10 minutes, and you can view the transaction id with 21 log. Once the transaction has been confirmed, you can check the balance in your bitcoin wallet from the command line with wallet balance, and you can send bitcoin from your wallet to another address with wallet sendto $BITCOIN_ADDRESS --satoshis $SATOSHI_AMOUNT --use-unconfirmed. The --satoshis flag allows you to specify the amount in satoshis; without it the sendto amount is in BTC, but this behavior is deprecated and will be removed soon. The --use-unconfirmed flag ensures that you can send even if you have unconfirmed transactions in your wallet.


Ready to sell your endpoint? Go to slack.21.co

Ready to try out your bitcoin-payable server in the wild? Or simply want to browse and purchase from other bitcoin-enabled servers? Head over to the 21 Developer Community at slack.21.co to join the bitcoin machine-payable marketplace hosted on the 21 peer-to-peer network.