Writing answering system using Python and YottaAnaswers API


We released our API for public use last year. In this tutorial, we will leverage this API to construct a basic responding application in Python. This is a part of series of tutorials.

YottaAnswers API

There are two versions of API, Public and Private. The Public version is free, and there is no need for registration to use this API. Downside of this version is that it has a rate-limit and that you will share the system with other Public users. If you want better performance, you should use the Private version, where you can register using email, where you will get your API key. It will give you 1000 requests per day, and 30000 requests overall.

Using Python for creating applications

Python is one of the most used programming languages and, thanks to its simplicity, is usually one of the first programming languages for new software developers. One of the major results of its wide use, is a big community with lots of support and huge amount of tools for software developers; we believe that API will be one more tool that will help to create any Q&A programs.

Let’s start

In this tutorial we need python3.7+ or newer version, also third party library for creating requests to our API, called requests.
Initializing project for python is easy, you only need to create file that ends with extension .py

yottaanswers$ touch api_example.py

After opening the python file, we will import two libraries: requests and json (part of python installation). JSON library is used to unpack API results to python readable objects.

import requests
import json

For part we will use public path to our API, and in code, its url is nedded. Also we need to create argumets that will be passed to API call. First argument is called payload and is used to pass real arguments, and it contans question that user is asking. Second argument are headers, metadata for proper contact with API. For this we only need to pass content type, which is json.

payload = {"question": question}
headers = {"Content-Type": "application/json"}

After that API is called using requests function request. Because API call is of type POST, we also need to pass that the function call. The function will return response, we are only interested in its attribute text, which contains returned data.
This data then will be loaded with json to python object, list of dictionaries.

response = requests.request("POST", url, json=payload, headers=headers)
results = json.loads(response.text)

After that we will iterate over results and print answers.

question = input("Question: ")

results = ask_question_public(question)
for ind,a in enumerate(results):
   print(f"{ind}) {a['answer']}")

For example, on question “When was Python 3 released?”, output is:

Question: When was Python 3 released?
0) in December 2008
1) released in 2008
2) on December 3, 2008
3) on 3 December 2008
4) 2010
5) together with the new module asyncio
6) after a long period of testing

Code for Private version

There is not much difference between codes for both versions of API. If you want to call the Private version, you need to add authorization to options and add privateQuestion to your path.

headers = {
      Authorization: 'Bearerey <YOUR API KEY>',
      'Content-Type': 'application/json'
    }

Full code

def ask_question_public(question):

    url = "https://api.yottaanswers.com/api/v1/publicQuestion"

    # question = "Who creates Galaxy phones"

    payload = {"question": question}
    headers = {"Content-Type": "application/json"}

    response = requests.request("POST", url, json=payload, headers=headers)

    if response.status_code != 200:
        return []

    results = json.loads(response.text)
    return results



if __name__=="__main__":
    while True:
        question = input("Question: ")

        if len(question.strip()) == 0:
            break
        results = ask_question_public(question)
        for ind,a in enumerate(results):
            print(f"{ind}) {a['answer']}")

Summary

In this post, we looked at how to create a simple answering system using YottaAnswers API. This API is a very simple and very powerful tool for every developer interested. We believe that there are endless possibilities with this API, but this should be a great start in your journey.

This is it for now. Thank you for reading. We hope this post was useful for giving you some idea of what you could do with API. Feel free to share your thoughts and ideas in the comments.


Leave a Reply

Required fields are marked *