JustToThePoint English Website Version
JustToThePoint en español

Maximize your online presence with our exclusive offer: Get a stunning hero banner, the hero you need and deserve, at an unbeatable price! Bew, 689282782, bupparchard@gmail.com

JSON and APIs with Python

Some websites make it easier for us to have direct access to their data with the use of an API. An API is a set of defined rules that explain how computers or applications communicate with one another. Typically, a company offers a set of dedicated URLs that provide access to their data in JSON format.

JSON is a lightweight, text-based, language-independent data interchange format. It is easy for humans to read and write. It is a key-value data format that is typically rendered in curly braces, similar to a Python dictionary.

import platform, socket, getmac, json, psutil

platform is used to get information about the underlying system/platform where our code runs. getmac is a package to get the MAC address of hosts on the local network. psutil is a library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python.

import pyperclip # Pyperclip is a cross-platform Python module for copy and paste clipboard functions.
def getSystemInfo():
    try:
        info={} # Create a dictionary. Dictionaries are used to store data values in key:value pairs.
        info['platform']=platform.system() # It returns the underlying platform, e.g. Linux, Windows.
        info['platform-release']=platform.release() # It returns the system's release, e.g. 5.11.0-38-generic.
        info['platform-version']=platform.version() # It returns the system’s release version, e.g. #42-Ubuntu SMP Fri Sep 24 14:03:54 UTC 2021.
        info['architecture']=platform.machine() # It returns the machine type, e.g, x86_64, i386.
        info['hostname']=socket.gethostname() # It returns the hostname of the machine.
        info['ip-address']=socket.gethostbyname(socket.gethostname()) # gethostbyname gets the IPv4 corresponding to a given Internet host name.
        info['mac-address']=getmac.get_mac_address() # It gets the MAC address of the machine.
        info['processor']=platform.processor() # It returns the processor name. However, many platforms do not provide this information and return the same value as machine.
        info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB"

psutil.virtual_memory().total returns the total physical memory, e.g. 8280530944 in bytes = 8 in GB (psutil.virtual_memory().total / (1024.0 **3) = psutil.virtual_memory().total / (1024.03). Notice that 1GB = 10241 MB = 10242 KB = 10243 bytes.

        info['clipboard']=pyperclip.paste() returns the content of the clipboard
        return json.dumps(info) # It converts a Python object into a json string.
    except Exception as e:
        print(e)

if __name__ == '__main__':
    print(getSystemInfo())

{“platform”: “Linux”, “platform-release”: “5.11.0-38-generic”, “platform-version”: “#42-Ubuntu SMP Fri Sep 24 14:03:54 UTC 2021”, “architecture”: “x86_64”, “hostname”: “MyLinux”, “ip-address”: “127.0.1.1”, “mac-address”: “81:d5:71:e9:41:1e”, “processor”: “x86_64”, “ram”: “8 GB”, “clipboard”: “JSON is a lightweight, text-based, language-independent data interchange format.”}

Jokes Generator with Python

canhazdadjoke.com can be used as an API for fetching a random joke. Furthermore, no authentication is required to use its API. GET https://icanhazdadjoke.com/ fetch a random dad joke.

$ curl -H "Accept: application/json" https://icanhazdadjoke.com/

{ “id”: “R7UfaahVfFd”, “joke”: “My dog used to chase people on a bike a lot. It got so bad I had to take his bike away.”, “status”: 200 }

import requests

The requests library is one of the most popular Python libraries. It is the standard for making HTTP requests in Python.

It is an elegant and simple HTTP library for Python that abstracts the complexities of making requests, so you can focus on interacting with services and consuming data in your application. To install Requests, simply run this command in your terminal: python -m pip install requests.

def getJokes():
    url = "https://icanhazdadjoke.com"
    headers = {"Accept": "application/json"} 

    try:
        r = requests.get(url, headers=headers)

This code calls requests.get() to send a GET request and retrieve resources from a given API. We can add HTTP headers to a request. Now, we have a Response object called r.

>>> type(r) 
>>> print(r.url) 
https://icanhazdadjoke.com/ 
>>> print(r.json()) 

Then, we call .json() on the response object to view the data that came back from the API. It returns a JSON object of the result. {‘id’: ‘GQuzAAXgah’, ‘joke’: ‘Some people say that I never got over my obsession with Phil Collins.\r\nBut take a look at me now.’, ‘status’: 200}

        joke = r.json()['joke'] # Finally, we can get the joke.
        print(joke)
        r2 = requests.get("http://api.icndb.com/jokes/random) # Let's fetch another joke from https://api.icndb.com.
>>> print(r2.json()) 
# The json() method returns the JSON we received in the API call as a python dictionary. 

{’type’: ‘success’, ‘value’: {‘id’: 342, ‘joke’: ‘Chuck Norris owns a chain of fast-food restaurants throughout the southwest. They serve nothing but barbecue-flavored ice cream and Hot Pockets.’, ‘categories’: []}}

        joke2 =  str(r2.json()['value']['joke'])
        print(joke2)
    except:
        return "No joke found."
if __name__ == "__main__":
    getJokes()

Doctor, I’ve broken my arm in several places” Doctor “Well don’t go to those places.”
If you try to kill -9 Chuck Norris’s programs, it backfires.

Weather Forecast in Python

Let’s see another example. Weather API is a simple, fast, and free weather API from OpenWeatherMap. We will use a free tier of their API. Go to its website, register for free, and login in to copy your API key.

import requests, credentials
def weather(city):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=' + credentials.API_KEY_OPENWEATHERMAP

API call: api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}

Storing credentials inside a credentials.py file is the simplest way to store your passwords safely. You can use environment variables, too.

# API key for currencyConverter.py 
Currency_API_KEY = "myPrivateApiKey".

Besides, you can use Postman instead of Python to explore an API more interactively.

    r = requests.get(url.format(city)).json()

The format() method formats the specified value (city) and insert it inside the string’s placeholder. The placeholder is defined using curly brackets: {}.

It returns: {‘coord’: {’lon’: -4.4203, ’lat’: 36.7202}, ‘weather’: [{‘id’: 804, ‘main’: ‘Clouds’, ‘description’: ‘overcast clouds’, ‘icon’: ‘04n’}], ‘base’: ‘stations’, ‘main’: {’temp’: 18.87, ‘feels_like’: 18.85, ’temp_min’: 16.77, ’temp_max’: 19.99, ‘pressure’: 1023, ‘humidity’: 78}, ‘visibility’: 10000, ‘wind’: {‘speed’: 2.57, ‘deg’: 280}, ‘clouds’: {‘all’: 90}, ‘dt’: 1634620547, ‘sys’: {’type’: 2, ‘id’: 2010336, ‘country’: ‘ES’, ‘sunrise’: 1634624917, ‘sunset’: 1634664978}, ’timezone’: 7200, ‘id’: 2514256, ’name’: ‘Málaga’, ‘cod’: 200}

    print("The weather in " + city + " is " + str(r['main']['temp']) + " °C.")
    
if __name__ == "__main__":
    weather('Malaga')

The weather in Malaga is 18.87 °C.

Getting Bitcoin price in real time using Python

Let’s get Bitcoin prices using Coindesk API.

import requests
def bitcoin():
    r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
    print ("The current price of Bitcoin is: " + r.json()['bpi']['USD']['rate'] + "$") 
if __name__ == "__main__":
    bitcoin()

The current price of Bitcoin is: 62,423.1633$

Getting our Daily News using Python

Let’s get the Daily News using Python. News API is a simple, easy-to-use REST API that returns JSON search results for current and historic news articles published by over 80,000 worldwide.

def news():
    main_url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=" + credentials.News_API_KEY
    # This endpoint provides live top and breaking headlines for a country (us); apiKey is the API key.

    # results is an empty list which will contain all news
    results = []
    # Let's fetch our data in json format
    r = requests.get(main_url).json()

print(r) will return

{‘status’: ‘ok’, ’totalResults’: 38, ‘articles’: [{‘source’: {‘id’: ‘fox-news’, ’name’: ‘Fox News’}, ‘author’: ‘Ryan Gaydos’, ’title’: ‘Titans stop Josh Allen on crucial 4th down to hold on for win, fans debate whether Bills made right play - Fox News’, ‘description’: ‘The Buffalo Bills found out Monday night football is truly a game of inches.’, ‘url’: ‘https://www.foxnews.com/sports/titans-stop-josh-allen-4th-down-win-fans-debate-play’, ‘urlToImage’: ‘https://static.foxnews.com/foxnews.com/content/uploads/2021/10/Josh-Allen5.jpg’, ‘publishedAt’: ‘2021-10-19T03:51:52Z’, ‘content’: ‘The Buffalo Bills found out Monday night football is truly a game of inches.\r\nThe phrase may be one of the oldest cliches in sports, but it was Bills quarterback Josh Allen who got the lesson in a 34… [+2684 chars]’}, {‘source’: {‘id’: ’nbc-news’, ’name’: ‘NBC News’}, …

    articles = r["articles"]
    print("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐")
    print("News provided by: News API, https://newsapi.org/")
    print("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐")
    i = 0
    # Let's walk through all the news headlines with a loop and print just the titles and descriptions.
    for article in articles:
        i = i + 1
        print(str(i) + ".- " + article["title"] + ". " + article["description"] + " " +  article["url"])
if __name__ == "__main__":
     news()

‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ News provided by: News API, https://newsapi.org/ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
1.- Titans stop Josh Allen on crucial 4th down to hold on for win, fans debate whether Bills made right play - Fox News. The Buffalo Bills found out Monday night football is truly a game of inches. https://www.foxnews.com/sports/titans-stop-josh-allen-4th-down-win-fans-debate-play

Bitcoin donation

JustToThePoint Copyright © 2011 - 2024 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.