Building an API to fetch data from the steem blockchain is actually easier than you might think. The easiest way I found and used to build the Steem-Buddy API is Python and Flask.
Flask is a micro web framework (a fancy word that actually means the handling of http requests) which allows you with just a few lines of python code to build an API (application programming interface).
Below is the complete Flask / Python code that runs my Steem-Buddy API on Heroku.
I am not an expert in python and Flask but will do my best to explain each line as accurate as possible.
from steemdata import SteemData
This line imports the SteemData helper library created by @furion. This library is required to easily access SteemData, a Mongo Database that contains steem blockchain information.
from flask import Flask, jsonify, request
The heart of the application. Flask is imported hear. In Addition we add the jsonify which is needed to return and display the fetched data in JSON format.
from flask_cors import CORS, cross_origin
This line is very important since it is needed to allow cross origin requests. I spent one whole day to figure out why I can't get my JSON data displayed on my front end hosted on AWS. This single line of code was needed to fix it!
app = Flask(__name__)
Initiate Flask app
CORS(app)
Initiate CORS extension
s = SteemData()
Declare variable "s" as SteemData database
#GET steemit.com users filtered by interest
@app.route('/steemians/<string:interest>')
def show_users(interest):
Initiate Flask Route with interest input and start show_users function which expects interest input.
steemians = list(s.Accounts.find({'json_metadata.profile.about': {'$regex': interest, '$options': "i"}},
projection={"name": 1, "_id": 0, "profile.location": 1, "profile.about": 1, "profile.profile_image": 1}))
Mongo DB query that looks for a matching interest in the profile.about key. In order to be efficient with the bandwidth I use projection to only get certain information like name, about, location and image.
return jsonify({'steemians': steemians})
Return the data in JSON format in order for my front end (Vue.js) to handle the data.
if __name__ == '__main__':
app.run(debug=True)
Run the Flask app if no errors found.
That's it, 16 lines of code to create an API.