Learn How To Use Web APIs in Python 3

python api
  • May 2, 2018
  • Vishnu

Application Program Interfaces (APIs) are regularly used to recover information from remote sites. Websites like Twitter, Reddit, and Facebook all offer certain data through their APIs. To utilize an API, you make a demand to a remote web server and recover the information you require.

An API makes it simple for developers to incorporate one application with another. They uncover some of a program’s internal workings limitedly. You can utilize APIs to get data from different projects or to automate things you regularly do in your web program.

Accessing Web Services

Python presents us with the JSON and simplejson modules to communicate with JSON.

JSON isbased on two structures:

  • A collection of name/value sets
  • An ordered value lists.

API Requests

When you write “www.google.com” in the address bar of the browser, your PC is really approaching the “www.google.com” server for a site page, to return to the browser.


APIs work similarly, your program requests for data. This information is generally returned in JSON configuration.

To get the information, we make a demand to a web server. So, the server replies with our data.

Getting Information From The Web API

We will learn how to use Python in the Digital Ocean API to recover data from your Digital Ocean account.

Your Digital Ocean account incorporates some regulatory data that you might not have found in the Web UI. An API can provide you an alternate view of familiar data. Simply observing this substitute view can often offer concepts regarding what you should need to do with an API or uncover administrations and choices you didn’t know.

Begin by making a task for the scripts. Make another directory for the task called apis:

           $ mkdirapis

Explore into this new directory:

           $ cd apis·         $ python3 -m venvapis

Make another virtualenv for this task:

           $ source apis/bin/activate

Activate the virtualenv:

          $source apis/bin/activate

Now install the requests library to use in scripts for making HTTP requests for scripts:

         (apis) $ pip install requests

With the configured environment, make another Python file called do_get_account.py. Open it in the text editor. By importing libraries begin this program off for working with JSON and HTTP requests.


import json

import requests

Python code is loaded with these import statements that make it less demanding to work with the JSON data format and the HTTP protocol. Use these libraries when you are not inspired by the subtle elements of how to parse and make substantial JSON or how to send HTTP requests.We simply need to utilize them to achieve these tasks.

Then, set up a few variables to hold data that in every request will be the same. This saves from the tiringexercise of typing it again and again. It also gives us a solitary place to create updates if anything changes. After the import statements, add these lines to the document.

do_get_account.py api_token = ‘your_api_token’ api_url_base = ‘https://api.digitalocean.com/v2/’

The api_token variable is a string for holding the Digital Ocean API token. Substitute the value in the case with your particular token. The api_url_base variable is the string that begins each URL in the Digital Ocean API.

Then, we have to set up the HTTP request headers the manner API docs depict. Add the given lines to the file to install a dictionary incorporating your request headers:

do_get_account.py headers = {‘Content-Type’: ‘application/json’, ‘Approval’: ‘Carrier {0}’.format(api_token)}

This sets two headers immediately.

The Content-Type header advises the server to demand JSON-formatted information in the request body.

The Authorization header has to incorporate the token.So, we utilize Python’s string formatting rationale to embed the api_token variable into the string as we make the string.

It’s an ideal moment to really send the request. Put this logic into a function which controls the request sending and perusing the response. You’ll wind up with code that’s not difficult to test and re-utilize.

The function will utilize the variables you made to send the request and restore the account data in a Python dictionary.

Characterize the function that gets the account data. It’s dependably a smart way to name a function after what it does. Let’s call it get_account_info:

do_get_account.py def get_account_info(): api_url = ‘{0}account’.format(api_url_base) reaction = requests.get(api_url, headers=headers) on the off chance that response.status_code == 200: return json.loads(response.content.decode(‘utf-8’)) else: return None

Create the value for api_url by utilizing Python’s string formatting strategy. Affix the API’s base URL before the string record to get the URL https://api.digitalocean.com/v2/account, the URL that should return account data.

The response variable contains a question made by the Python requests module. This line sends the request to the URL was created with the headers we characterized toward the beginning of the script and returns the API response.

Now, we take a look at the HTTP status code of the response.

In case it’s 200, a successful response, at that point to load a string as JSON we’ll utilize the json module’s loads function. The string loaded is the response object content, response.content. The .decode(‘utf-8’) section reveals to Python that the content is encoded utilizing the UTF-8 character set, as every response from the DigitalOcean API will be. The JSON module makes an object from that, which is used for this function as the return value.

In case the response was not 200, at that point, we return None, which is an exceptional value in Python. Check this when we call this function. You’ll see that we’re simply neglecting any mistakes now. This is to retain the clear “success” logic.

Presently call this function, check to ensure it got a decent response, and print out the subtle elements that the API returned:

account_info = get_account_info() sets the account_info variable to what returned from the call to get_account_info(), so it can be the exceptional value None or it can be the data collection about the account.

If it is not None, at that point, we print out each snippet of data on its particular line by utilizing the items() strategy that all the Python dictionaries hold.

Else (that is if account_info is None), we’ll print the error message.

Thus, now you know how to use API to recover data.

Related posts

2018-07-18 05:03:17

13 Best Python Web Framework For Web Developers

Read more
2018-07-11 09:23:00

Top 100 Python Interview Questions and Answers

Read more
2018-07-06 07:09:21

Developing a Chatbot using Python Language: Tutorial

Read more


Web Development Company