How to get a new API response in a Tkinter textbox?


APIs are extremely useful in implementing a service or feature in an application. APIs help to establish the connection between the server and a client, so whenever a client sends a request using one of the API methods to the server, the server responds with a status code (201 as a successful response) to the client.

You can make a request to any API you want using one of the methods (GET, POST, PUT or DELETE). However, if you want to create an application where you need a request to the server using one of the publicly available API (for example, Cat Facts API), then you can use the requests module in the Python library.

In the following application, we will create a textbox which will display the response (text) retrieved from the server using one of the Cat Facts API. You will also need to make sure that you have already installed the requests module in your environment. To install requests module, you can use the following command,

pip install requests

Once the requests module has been successfully installed, you can follow the steps given below to create an application −

  • Import all the required libraries.

  • Create a text widget in the application to display all the responses which are retrieved from the server (GET requests).

  • Create a var to store the API URL.

  • Define a function to call the API and retrieve the JSON response by extracting the "fact" attribute from the response body.

  • Update the text widget with the response by deleting the existing fact and inserting the new fact.

  • Create a button (next and exit) to load random Cat facts seamlessly.

Example

# Import the required libraries
from tkinter import *
import requests
import json

# Create an instance of tkinter frame
win = Tk()
win.geometry("700x350")
win.title("Cat Fact API ")

# Create a text box to display the response body
text = Text(win, height=10, width=50, wrap="word")
text.config(font="Arial, 12")

# Create a label widget
label = Label(win, text="Cat Facts")
label.config(font="Calibri, 14")

# Add the API URL
api_url = "https://catfact.ninja/fact"

# Define a function to retrieve the response
# and text attribute from the JSON response
def get_zen():
   response = requests.get(api_url).text
   response_info = json.loads(response)
   Fact = response_info["fact"]
   text.delete('1.0', END)
   text.insert(END, Fact)

# Create Next and Exit Button
b1 = Button(win, text="Next", command=get_zen)
b2 = Button(win, text="Exit", command=win.destroy)

label.pack()
text.pack()
b1.pack()
b2.pack()

get_zen()

win.mainloop()

Output

Click the "Next" button to fetch the next random Cat facts. You can also click the "Exit" button to quit out of the tkinter application window.

Updated on: 16-Dec-2021

911 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements