/ python

Playing with APIs and Python

Most cloud based software these days allows you to programmatically interact with it's API. It's essential to automation! For example let's say you built an embedded software on a convertible. You want the convertible to automatically pull down it's top if the weather is nice. Now let's assume that you have no sensor on convertible that can track the weather, but it does have internet connectivity...  

How are we going to track the weather with the internet? Simple, with API's specifically from a weather website!

First, what is an API? An API is an application programming interface, it allows custom made scripts or software to interact with other software seamlessly without knowing the code base of the other software.

Let's explore this magical thing called "API". Download Postman, Postman is a free app that will aid us in exploring APIs. There are millions of APIs to play with; Google, Microsoft, and AWS offer some very popular APIs, however there are limits on the amount of API calls you can make to these and may require API keys. So we'll play with the API's from these https://jsonplaceholder.typicode.com/.

Postman

Jsonplaceholder gives us the following endpoints to test out. We'll test https://jsonplaceholder.typicode.com/posts?userId=1 and see what it returns.

Fire up Postman and let's give this API thing a test. Make sure the method is set to "GET" and paste the endpoint (https://jsonplaceholder.typicode.com/posts?userId=1) in the params bar.

Press "Send" and let's look at the output. Cool, it gave us data in json format, from here we can filter the data and extract what we need.

[
    {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
        "userId": 1,
        "id": 2,
        "title": "qui est esse",
        "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
    },
    {
        "userId": 1,
        "id": 3,
        "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
        "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
    },
    {
        "userId": 1,
        "id": 4,
        "title": "eum et est occaecati",
        "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
    },
    {
        "userId": 1,
        "id": 5,
        "title": "nesciunt quas odio",
        "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
    },
    {
        "userId": 1,
        "id": 6,
        "title": "dolorem eum magni eos aperiam quia",
        "body": "ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae"
    },
    {
        "userId": 1,
        "id": 7,
        "title": "magnam facilis autem",
        "body": "dolore placeat quibusdam ea quo vitae\nmagni quis enim qui quis quo nemo aut saepe\nquidem repellat excepturi ut quia\nsunt ut sequi eos ea sed quas"
    },
    {
        "userId": 1,
        "id": 8,
        "title": "dolorem dolore est ipsam",
        "body": "dignissimos aperiam dolorem qui eum\nfacilis quibusdam animi sint suscipit qui sint possimus cum\nquaerat magni maiores excepturi\nipsam ut commodi dolor voluptatum modi aut vitae"
    },
    {
        "userId": 1,
        "id": 9,
        "title": "nesciunt iure omnis dolorem tempora et accusantium",
        "body": "consectetur animi nesciunt iure dolore\nenim quia ad\nveniam autem ut quam aut nobis\net est aut quod aut provident voluptas autem voluptas"
    },
    {
        "userId": 1,
        "id": 10,
        "title": "optio molestias id quia eum",
        "body": "quo et expedita modi cum officia vel magni\ndoloribus qui repudiandae\nvero nisi sit\nquos veniam quod sed accusamus veritatis error"
    }
]

We'll shift gears from here and fire up the Pycharm or whatever python IDE you prefer. We're going to need to import the requests library so python can interact with jsonplaceholder's API.

Your code should look something similar to this:

import requests

apiURL = "https://jsonplaceholder.typicode.com/posts?userId=1"
apiRequest = requests.get(apiURL)

print(apiRequest.text)

Now when you run this code, it should output the same output as what we saw in Postman.

API Keys

If you remember earlier in this post I mentioned that some APIs require API keys? Now I'm going to show you how to interact with APIs that need them. We'll test this on a web application called Thingworx. Thingworx has an API endpoint /Thingworx/Subsystems/PlatformSubsystem/Services/GetThingworxVersion that returns the version that is installed.

We'll test it on Postman and we'll see what it returns.

As you can see it returned the Thingworx version (7.4.0-b159).

Time to do the same thing on python. Let's return to Pycharm and import re and requests libraries. The re library is important so that we can filter out the extraneous data with regex!

Below is my example code. As you can see I'm passing the API key in the header. Then I'm making a post request to interact with the endpoint. Then I used a regex to grab just the Thingworx version. When you run the code below it returns the version only.

import requests, re

apiURL = "https://test-environment-thingworx.com/Thingworx/Subsystems/PlatformSubsystem/Services/GetThingworxVersion"

payload = {
    "appkey":"354a752d-e841-4127-b6ff-e15b246a3926",
    "Content-Type": "application/json"
}

#### POST REQUEST ####
apiRequest = requests.post(apiURL, headers=payload)

#### REGEX FOR THE TWX VERSION ####
apiRegex = re.compile(r'\d\.\d\.\d\d?\-\w\d\d\d?')

#### APPLYING THE REGEX ON POST REQUEST OUTPUT ####
results = apiRegex.search(apiRequest.text)

print(results.group())

Back to the fictitious convertible software...

I thought I'd point you in the right direction on this one. I'm going to use Yahoo Weather since it doesn't need an API key, however you're limited to 2,000 calls per day.

Once you have Yahoo Weather opened replace city and state with whatever you prefer. I live in Boston so I went with that.

Notice at the bottom box titled "Endpoint", this is the URL we are going to use so that our app can figure out the weather for the day. As you can see in the response it shoots out very detailed data which you can filter out to get the data to see if the weather is going to be sunny.  

Playing with APIs and Python
Share this