APIs

3.1. APIs#

API stand for Application Programming Interface. APIs are a way for computers to talk to each other. They are a set of rules that allow one piece of software application to talk to another. APIs are used to share data between applications.

Many companies provide APIs to allow developers to access their services. For example, Twitter provides an API that allows programmers to access their service and get tweets and other information. Google provides APIs for many of their services, including Google Maps, Google Drive, and Google Calendar.

APIs are used to connect to other applications. For example, you can use the Twitter API to read and write tweets from your own application. You can use the Google Maps API to get directions from one place to another. You can use the Google Translate API to translate text from one language to another.

Most APIs require you to register for an API key. This is a unique identifier that allows the API to track your usage. You can get an API key by registering for an account with the service provider. For example, if you want to use the Twitter API, you need to register for a Twitter account and then request an API key.

Most APIs are free to use, but some require you to pay a fee. For example, the Google Maps API is free for up to 25,000 requests per day, but you have to pay if you want to make more than that. The Google Translate API is free for up to 500,000 characters per month, but you have to pay if you want to translate more than that.

Most APIs return data in the following formats: JSON, XML, or CSV. JSON is the most common format, but some APIs return data in XML or CSV format. You can use the requests library to make HTTP requests to APIs and get data in JSON format.

3.1.1. JSON#

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.

  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

In JSON, they take on these forms:

  • An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

  • An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

  • A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

  • A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

  • A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

  • White space can be inserted between any pair of tokens. Excepting a few encoding details, that completely describes the language.

Here is a small example:

{
    "firstName": "John",
    "lastName": "Smith",
    "age": 25,
    "address": {
        "streetAddress": "21 2nd Street",
        "city": "New York",
        "state": "NY",
        "postalCode": "10021"
    },
    "phoneNumber": [
        {
            "type": "home",
            "number": "212 555-1234"
        },
        {
            "type": "fax",
            "number": "646 555-4567"
        }
    ]
}

An example of a public API that returns data in JSON format is the Open Notify API. This API returns the current location of the International Space Station in JSON format.

{
  "iss_position": {
    "latitude": "-50.7353",
    "longitude": "-179.9974"
  },
  "message": "success",
  "timestamp": 1619455654
}
'''Example code that makes an API call to Open Notify API'''

import requests

# Make an API call and store the response.

url = 'http://api.open-notify.org/astros.json'

response = requests.get(url)

# Print the status code of the response.

print(f"Status code: {response.status_code}")

# Store API response in a variable.

response_dict = response.json()

# Print the number of people currently in space.

print(f"People in space: {response_dict['number']}")

# Print the names of people currently in space.

for person in response_dict['people']:

    print(person['name'])

# Print the raw response.

print(response.text)

# Print the raw response as a list.

print(response.json())

# Print the raw response as a dictionary.

print(response.json()['people'])

# Print the raw response as a dictionary.

print(response.json()['people'][0])

# Print the raw response as a dictionary.

print(response.json()['people'][0]['name'])
Status code: 200
People in space: 10
Sergey Prokopyev
Dmitry Petelin
Frank Rubio
Stephen Bowen
Warren Hoburg
Sultan Alneyadi
Andrey Fedyaev
Jing Haiping
Gui Haichow
Zhu Yangzhu
{"number": 10, "people": [{"name": "Sergey Prokopyev", "craft": "ISS"}, {"name": "Dmitry Petelin", "craft": "ISS"}, {"name": "Frank Rubio", "craft": "ISS"}, {"name": "Stephen Bowen", "craft": "ISS"}, {"name": "Warren Hoburg", "craft": "ISS"}, {"name": "Sultan Alneyadi", "craft": "ISS"}, {"name": "Andrey Fedyaev", "craft": "ISS"}, {"name": "Jing Haiping", "craft": "Tiangong"}, {"name": "Gui Haichow", "craft": "Tiangong"}, {"name": "Zhu Yangzhu", "craft": "Tiangong"}], "message": "success"}
{'number': 10, 'people': [{'name': 'Sergey Prokopyev', 'craft': 'ISS'}, {'name': 'Dmitry Petelin', 'craft': 'ISS'}, {'name': 'Frank Rubio', 'craft': 'ISS'}, {'name': 'Stephen Bowen', 'craft': 'ISS'}, {'name': 'Warren Hoburg', 'craft': 'ISS'}, {'name': 'Sultan Alneyadi', 'craft': 'ISS'}, {'name': 'Andrey Fedyaev', 'craft': 'ISS'}, {'name': 'Jing Haiping', 'craft': 'Tiangong'}, {'name': 'Gui Haichow', 'craft': 'Tiangong'}, {'name': 'Zhu Yangzhu', 'craft': 'Tiangong'}], 'message': 'success'}
[{'name': 'Sergey Prokopyev', 'craft': 'ISS'}, {'name': 'Dmitry Petelin', 'craft': 'ISS'}, {'name': 'Frank Rubio', 'craft': 'ISS'}, {'name': 'Stephen Bowen', 'craft': 'ISS'}, {'name': 'Warren Hoburg', 'craft': 'ISS'}, {'name': 'Sultan Alneyadi', 'craft': 'ISS'}, {'name': 'Andrey Fedyaev', 'craft': 'ISS'}, {'name': 'Jing Haiping', 'craft': 'Tiangong'}, {'name': 'Gui Haichow', 'craft': 'Tiangong'}, {'name': 'Zhu Yangzhu', 'craft': 'Tiangong'}]
{'name': 'Sergey Prokopyev', 'craft': 'ISS'}
Sergey Prokopyev

Some popular APIs that return data in JSON format are:

3.1.2. XML#

XML stands for Extensible Markup Language. It is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The design goals of XML emphasize simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.

Several schema systems exist to aid in the definition of XML-based languages, while programmers have developed many application programming interfaces (APIs) to aid the processing of XML data.

XML data is made up of storage units called entities, which contain either parsed or unparsed data. Parsed data is made up of characters, some of which form character data, and some of which form markup. Markup encodes a description of the document’s storage layout and logical structure. XML provides a mechanism to impose constraints on the storage layout and logical structure.

An example of XML data is shown below:

<?xml version="1.0" encoding="UTF-8"?>

<breakfast_menu>
    <food>
        <name>Belgian Waffles</name>
        <price>$5.95</price>
        <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
        <calories>650</calories>
    </food>
    <food>
        <name>Strawberry Belgian Waffles</name>
        <price>$7.95</price>
        <description>Light Belgian waffles covered with strawberries and whipped cream</description>
        <calories>900</calories>
    </food>
    <food>
        <name>Berry-Berry Belgian Waffles</name>
        <price>$8.95</price>
        <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
        <calories>900</calories>
    </food>
    <food>
        <name>French Toast</name>
        <price>$4.50</price>
        <description>Thick slices made from our homemade sourdough bread</description>
        <calories>600</calories>
    </food>
    <food>
        <name>Homestyle Breakfast</name>
        <price>$6.95</price>
        <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
        <calories>950</calories>
    </food>

</breakfast_menu>
'''Example of an API that returns XML '''

import requests

url = 'http://api.open-notify.org/astros.xml'

response = requests.get(url)

print(response.text)