Getting Started with APIs – Dataquest

[ad_1]

python api tutorial about the ISS

On this Python API tutorial, we’ll discover ways to retrieve knowledge for knowledge science initiatives. There are hundreds of thousands of APIs on-line which offer entry to knowledge. Web sites like Reddit, Twitter, and Facebook all provide sure knowledge via their APIs.

To make use of an API, you make a request to a distant net server, and retrieve the info you want.

However why use an API as a substitute of a static CSV dataset you’ll be able to obtain from the net? APIs are helpful within the following circumstances:

  • The information is altering rapidly. An instance of that is inventory worth knowledge. It doesn’t actually make sense to regenerate a dataset and obtain it each minute — this may take quite a lot of bandwidth, and be fairly sluggish.
  • You desire a small piece of a a lot bigger set of information. Reddit feedback are one instance. What if you wish to simply pull your individual feedback on Reddit? It doesn’t make a lot sense to obtain the whole Reddit database, then filter simply your individual feedback.
  • There’s repeated computation concerned. Spotify has an API that may let you know the style of a chunk of music. You can theoretically create your individual classifier, and use it to compute music classes, however you’ll by no means have as a lot knowledge as Spotify does.

In circumstances like those above, an API is the appropriate answer. On this weblog submit, we’ll be querying a easy API to retrieve knowledge in regards to the International Space Station (ISS).

About this Python API Tutorial

This tutorial is predicated on a part of our interactive course on APIs and Webscraping in Python, which you’ll be able to start for free.

For this tutorial, we assume that you realize a number of the fundamentals of working with knowledge in Python. In the event you don’t, you may wish to attempt our free Python Fundamentals course.

In the event you’re on the lookout for one thing extra superior, try our Intermediate API tutorial.

What’s an API?

An API, or Utility Programming Interface, is a server that you need to use to retrieve and ship knowledge to utilizing code. APIs are mostly used to retrieve knowledge, and that would be the focus of this newbie tutorial.

After we wish to obtain knowledge from an API, we have to make a request. Requests are used everywhere in the net. For example, whenever you visited this weblog submit, your net browser made a request to the Dataquest net server, which responded with the content material of this net web page. 

r api tutorial api request

API requests work in precisely the identical approach – you make a request to an API server for knowledge, and it responds to your request.

Making API Requests in Python

With a view to work with APIs in Python, we’d like instruments that may make these requests. In Python, the commonest library for making requests and dealing with APIs is the requests library. The requests library isn’t a part of the usual Python library, so that you’ll want to put in it to get began.

In the event you use pip to handle your Python packages, you’ll be able to set up requests utilizing the next command:

pip set up requests

In the event you use conda, the command you’ll want is:

conda set up requests

When you’ve put in the library, you’ll have to import it. Let’s begin with that necessary step: 

Now that we’ve put in and imported the requests library, let’s begin utilizing it.

Making Our First API Request

There are a lot of various kinds of requests. Essentially the most generally used one, a GET request, is used to retrieve knowledge. As a result of we’ll simply be working with retrieving knowledge, our focus will likely be on making ‘get’ requests.

After we make a request, the response from the API comes with a response code which tells us whether or not our request was profitable. Response codes are necessary as a result of they instantly inform us if one thing went unsuitable.

To make a ‘GET’ request, we’ll use the requests.get() function, which requires one argument — the URL we wish to make the request to. We’ll begin by making a request to an API endpoint that doesn’t exist, so we are able to see what that response code seems to be like. 

response = requests.get("http://api.open-notify.org/this-api-doesnt-exist")

The get() perform returns a response object. We are able to use the response.status_code attribute to obtain the standing code for our request:

print(response.status_code)

The ‘404’ standing code could be acquainted to you — it’s the standing code {that a} server returns if it may possibly’t discover the file we requested. On this case, we requested for this-api-doesnt-exist which (shock, shock) didn’t exist!

Let’s be taught a little bit extra about widespread standing codes.

API Standing Codes

Standing codes are returned with each request that’s made to an online server. Standing codes point out details about what occurred with a request. Listed below are some codes which can be related to GET requests:

  • 200: The whole lot went okay, and the end result has been returned (if any).
  • 301: The server is redirecting you to a special endpoint. This may occur when an organization switches domains, or an endpoint title is modified.
  • 400: The server thinks you made a nasty request. This may occur whenever you don’t ship alongside the appropriate knowledge, amongst different issues.
  • 401: The server thinks you’re not authenticated. Many APIs require login ccredentials, so this occurs whenever you don’t ship the appropriate credentials to entry an API.
  • 403: The useful resource you’re making an attempt to entry is forbidden: you don’t have the appropriate permissions to see it.
  • 404: The useful resource you tried to entry wasn’t discovered on the server.
  • 503: The server just isn’t able to deal with the request.

You may discover that all the standing codes that start with a ‘4’ point out some kind of error. The primary variety of standing codes point out their categorization. That is helpful — you’ll be able to know that in case your standing code begins with a ‘2’ it was profitable and if it begins with a ‘4’ or ‘5’ there was an error. In the event you’re you’ll be able to read more about status codes here.

API Documentation

With a view to guarantee we make a profitable request, after we work with APIs it’s necessary to seek the advice of the documentation. Documentation can appear scary at first, however as you employ documentation increasingly more you’ll discover it will get simpler.

We’ll be working with the Open Notify API, which provides entry to knowledge in regards to the worldwide area station. It’s an incredible API for studying as a result of it has a quite simple design, and doesn’t require authentication. We’ll educate you learn how to use an API that requires authentication in a later submit.

Usually there will likely be a number of APIs obtainable on a specific server. Every of those APIs are generally referred to as endpoints. The primary endpoint we’ll use is http://api.open-notify.org/astros.json, which returns knowledge about astronauts presently in area.

In the event you click on the hyperlink above to take a look at the documentation for this endpoint, you’ll see that it says This API takes no inputs. This makes it a easy API for us to get began with. We’ll begin by making a GET request to the endpoint utilizing the requests library: 

response = requests.get("http://api.open-notify.org/astros.json")
print(response.status_code)
200

We acquired a ‘200’ code which tells us our request was profitable. The documentation tells us that the API response we’ll get is in JSON format. Within the subsequent part we’ll study JSON, however first let’s use the response.json() method to see the info we acquired again from the API:

{'message': 'success', 'folks': [{'name': 'Alexey Ovchinin', 'craft': 'ISS'}, {'name': 'Nick Hague', 'craft': 'ISS'}, {'name': 'Christina Koch', 'craft': 'ISS'}, {'name': 'Alexander Skvortsov', 'craft': 'ISS'}, {'name': 'Luca Parmitano', 'craft': 'ISS'}, {'name': 'Andrew Morgan', 'craft': 'ISS'}], 'quantity': 6}

Working with JSON Knowledge in Python

JSON (JavaScript Object Notation) is the language of APIs. JSON is a solution to encode knowledge buildings that ensures that they’re simply readable by machines. JSON is the first format during which knowledge is handed forwards and backwards to APIs, and most API servers will ship their responses in JSON format.

You might need observed that the JSON output we acquired from the API appeared prefer it contained Python dictionaries, lists, strings and integers. You may consider JSON as being a mixture of those objects represented as strings. Let’s take a look at a easy instance: 

Python has nice JSON help with the json package. The json bundle is a part of the usual library, so we don’t have to put in something to make use of it. We are able to each convert lists and dictionaries to JSON, and convert strings to lists and dictionaries. Within the case of our ISS Go knowledge, it’s a dictionary encoded to a string in JSON format.

The json library has two primary capabilities:

  • json.dumps() — Takes in a Python object, and converts (dumps) it to a string.
  • json.loads() — Takes a JSON string, and converts (hundreds) it to a Python object.

The dumps() perform is especially helpful as we are able to use it to print a formatted string which makes it simpler to grasp the JSON output, like within the diagram we noticed above: 

import json

def jprint(obj):
    
    textual content = json.dumps(obj, sort_keys=True, indent=4)
    print(textual content)

jprint(response.json())
{
    "message": "success",
    "quantity": 6,
    "folks": [
        {
            "craft": "ISS",
            "name": "Alexey Ovchinin"
        },
        {
            "craft": "ISS",
            "name": "Nick Hague"
        },
        {
            "craft": "ISS",
            "name": "Christina Koch"
        },
        {
            "craft": "ISS",
            "name": "Alexander Skvortsov"
        },
        {
            "craft": "ISS",
            "name": "Luca Parmitano"
        },
        {
            "craft": "ISS",
            "name": "Andrew Morgan"
        }
    ]
}

Instantly we are able to perceive the construction of the info extra simply – we are able to see that their are six folks presently in area, with their names present as dictionaries inside an inventory.

If we evaluate this to the documentation for the endpoint we’ll see that this matches the desired output for the endpoint.

Utilizing an API with Question Parameters

The http://api.open-notify.org/astros.json endpoint we used earlier doesn’t take any parameters. We simply ship a GET request and the API sends again knowledge in regards to the variety of folks presently in area.

It’s quite common, nevertheless, to have an API endpoint that requires us to specify parameters. An instance of this the http://api.open-notify.org/iss-pass.json endpoint. This endpoint tells us the following instances that the worldwide area station will cross over a given location on the earth.

If we take a look at the documentation, it specifies required lat (latitude) and lengthy (longitude) parameters.

We are able to do that by including an elective key phrase argument, params, to our request. We are able to make a dictionary with these parameters, after which cross them into the requests.get perform. Right here’s what our dictionary would appear like, utilizing coordinates for New York Metropolis: 

parameters = {
    "lat": 40.71,
    "lon": -74
}

We are able to additionally do the identical factor immediately by including the parameters on to the URL. like this: http://api.open-notify.org/iss-pass.json?lat=40.71&lon;=-74.

It’s virtually all the time preferable to setup the parameters as a dictionary, as a result of requests takes care of some issues that come up, like correctly formatting the question parameters, and we don’t want to fret about inserting the values into the URL string.

Let’s make a request utilizing these coordinates and see what response we get. 

response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)

jprint(response.json())
{
    "message": "success",
    "request": {
        "altitude": 100,
        "datetime": 1568062811,
        "latitude": 40.71,
        "longitude": -74.0,
        "passes": 5
    },
    "response": [
        {
            "duration": 395,
            "risetime": 1568082479
        },
        {
            "duration": 640,
            "risetime": 1568088118
        },
        {
            "duration": 614,
            "risetime": 1568093944
        },
        {
            "duration": 555,
            "risetime": 1568099831
        },
        {
            "duration": 595,
            "risetime": 1568105674
        }
    ]
}

Understanding the Go Occasions

The JSON response matches what the documentation specified:

  • A dictionary with three keys
  • The third key, response, comprises an inventory of cross instances
  • Every cross time is a dictionary with risetime (cross begin time) and length keys.

Let’s extract the cross instances from our JSON object: 

pass_times = response.json()['response']
jprint(pass_times)
[
    {
        "duration": 395,
        "risetime": 1568082479
    },
    {
        "duration": 640,
        "risetime": 1568088118
    },
    {
        "duration": 614,
        "risetime": 1568093944
    },
    {
        "duration": 555,
        "risetime": 1568099831
    },
    {
        "duration": 595,
        "risetime": 1568105674
    }
]

Subsequent we’ll use a loop to extract simply the 5 risetime values: 

risetimes = []

for d in pass_times:
    time = d['risetime']
    risetimes.append(time)

print(risetimes)
[1568082479, 1568088118, 1568093944, 1568099831, 1568105674]

These instances are obscure – they’re in a format often known as timestamp or epoch. Primarily the time is measured within the variety of seconds since January 1st 1970. We are able to use the Python datetime.fromtimestamp() method to transform these into simpler to grasp instances:

from datetime import datetime

instances = []

for rt in risetimes:
    time = datetime.fromtimestamp(rt)
    instances.append(time)
    print(time)
2019-09-09 21:27:59
2019-09-09 23:01:58
2019-09-10 00:39:04
2019-09-10 02:17:11
2019-09-10 03:54:34

It seems to be just like the ISS passes over New York Metropolis usually – the following 5 instances occur inside a seven hour interval!

Python API Tutorial: Subsequent Steps

On this tutorial, we realized:

  • What an API is
  • Varieties of requests and response codes
  • How you can make a get request
  • How you can make a request with parameters
  • How you can show and extract JSON knowledge from an API

These basic steps will enable you to to start out working with APIs. Keep in mind that key to every time we used the API was to rigorously learn the API documentation and use that to grasp what request to make and what parameters to offer.

Now you’ve accomplished our Python API tutorial, you may wish to:



[ad_2]

Source link

Write a comment