Python API Tutorials

How to use an API with Python (Beginner’s Guide)

Nowadays, Python is one of the most popular and accessible programming languages. In 2019 it was ranked third in the TIOBE rating. Many experts believe that in 3-4 years it will overtake C and Java to lead the ratings.

Based on this, it would not be surprising if you use Python for your next API interaction project. In this article, we will talk about the wisdom of using the API and why Python will be a great help in this task.

Browse the Best Free APIs List

What is a REST API (from a Python perspective)

Firstly, let’s define an API.

An API (Application Programming Interface) is a set of rules that are shared by a particular service. These rules determine in which format and with which command set your application can access the service, as well as what data this service can return in the response. The API acts as a layer between your application and external service. You do not need to know the internal structure and features of the service, you just send a certain simple command and receive data in a predetermined format.

REST API (Representational state transfer) is an API that uses HTTP requests for communication with web services.

It must comply with certain constraints. Here are some of them:

  1. Client-server architecture – the client is responsible for the user interface, and the server is responsible for the backend and data storage. Client and server are independent and each of them can be replaced.
  2. Stateless – no data from the client is stored on the server side. The session state is stored on the client side.
  3. Cacheable – clients can cache server responses to improve performance.

A complete list of constraints you can see here.

From the Python side, the REST API can be viewed as a data source located on an Internet address that can be accessed in a certain way through certain libraries.

Types of Requests

Types of Requests or HTTP Request Methods characterize what action we are going to take by referring to the API.

In total, there are four main types of actions:

  • GET: retrieve information (like search results). This is the most common type of request. Using it, we can get the data we are interested in from those that the API is ready to share.
  • POST: adds new data to the server. Using this type of request, you can, for example, add a new item to your inventory.
  • PUT: changes existing information. For example, using this type of request, it would be possible to change the color or value of an existing product.
  • DELETE: deletes existing information

Prerequisites

In order to start working with the REST API through Python, you will need to connect a library to send HTTP requests.

The choice of the library depends on the version of Python.

If you use Python 2, we recommend using unirest because of its simplicity, speed, and ability to work with synchronous and asynchronous requests.

If you work with Python 3, then we recommend stopping the choice on requests that is the de facto standard for making HTTP requests in Python.

Further in our tutorial we will use Python 3.6 together with the requests library. That’s how the implementation of GET request will look using the requests:

import requests
response = requests.get('https://google.com/')
print(response)
>> <Response [200]>

Request returns а Response, a powerful object for inspecting the results of the request. Using Response, you can examine the headers and contents of the response, get a dictionary with data from JSON in the response, and also determine how successful our access to the server was by the response code from it. In our example, the response code was 200, which means that the request was successful. We will study the response codes and their values in a little more detail.

Status Codes

Status codes are returned with a response after each call to the server. They briefly describe the result of the call. There is a large number of status codes, we give those that you will most often meet:

  • 200 – OK. The request was successful. The answer itself depends on the method used (GET, POST, etc.) and the API specification.
  • 204 – No Content. The server successfully processed the request and did not return any content.
  • 301 – Moved Permanently. The server responds that the requested page (endpoint) has been moved to another address and redirects to this address.
  • 400 – Bad Request. The server cannot process the request because the client-side errors (incorrect request format).
  • 401 – Unauthorized. Occurs when authentication was failed, due to incorrect credentials or even their absence.
  • 403 – Forbidden. Access to the specified resource is denied.
  • 404 – Not Found. The requested resource was not found on the server.
  • 500 – Internal Server Error. Occurs when an unknown error has occurred on the server.

The request library has several useful properties for working with status codes. For example, you can simply view the status of the response code by accessing .status_code:

print(response.status_code)
>>> 200

That’s not all. You can use Response instance in a conditional expression. It will evaluate to True if the status code was between 200 and 400, and False otherwise.

if response:
  print('Request is successful.')
else:
  print('Request returned an error.')

Endpoints

In order to work with REST APIs, it is important to understand what an Endpoint is.

Usually, an Endpoint is a specific address (for example, https://weather-in-london.com/forecast), by referring to which you get access to certain features/data (in our case – the weather forecast for London). Commonly, the name (address) of the endpoint corresponds to the functionality it provides.

To learn more about endpoints, we will look at simple API example within the RapidAPI service. This service is an API Hub providing the ability to access thousands of different APIs. Another advantage of RapidAPI is that you can access endpoints and test the work of the API directly in its section within the RapidAPI service.

Let’s take for example the Dino Ipsum API. This API is used to generate any amount of Lorem Ipsum placeholder text. It is useful when you prototype or test the interface of your application and want to fill it with any random content.

In order to find Dino Ipsum API section, enter its name in the search box in the RapidAPI service or go to the “Other” category from “All Categories” list and select this API from the list. Dino Ipsum API through RapidAPI is free, so you can get as much placeholder text as you want.

Once you select Dino Ipsum API, the first page you’ll see is the API Endpoints subsection. This includes most of the information needed to get started. The API Endpoints subsection includes navigation, a list of endpoints (just one for this API), the documentation of the currently selected endpoint, and a code snippet (available in 8 different programming languages) to help you get started with your code.

We will examine the only endpoint this API has – dinos list, which returns a certain amount of placeholder text, depending on the entered parameters. As we are practicing in Python now, we want to get a Python snippet and test it in our app. Fill in required parameters (format=text, words=10, paragraphs=1) and here is our snippet:

response = unirest.get("https://alexnormand-dino-ipsum.p.rapidapi.com/?format=text&words=10&paragraphs=1",
  headers={
    "X-RapidAPI-Host": "alexnormand-dino-ipsum.p.rapidapi.com",
    "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  }
)

To use it with Python 3.6, we need to change unirest to requests. So, we get such an app:

import requests

words = 30
paragraphs = 1
formats = 'text'

response = requests.get(f"https://alexnormand-dino-ipsum.p.rapidapi.com/?format={formats}&words={words}&paragraphs={paragraphs}",
 headers={
   "X-RapidAPI-Host": "alexnormand-dino-ipsum.p.rapidapi.com",
   "X-RapidAPI-Key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 }
)

print(response.text)

Our app will call the endpoint, which is located at https://alexnormand-dino-ipsum.p.rapidapi.com/ and will print for us this nice placeholder text:

Craterosaurus Europasaurus Santanaraptor Dynamosaurus Pachyrhinosaurus Cardiodon Dakosaurus Kakuru Gracilisuchus Piveteausaurus.

Browse APIs

Getting a JSON response from an API request

Often REST API returns a response in JSON format for ease of further processing. The requests library has a convenient .json() method for this case that converts JSON to a Python object.

The already familiar Dino Ipsum API will help us test this functionality. We can get JSON from it in response if we specify the format = JSON parameter when accessing dinos list endpoint.

import requests

params = {"words": 10, "paragraphs": 1, "format": "json"}

response = requests.get(f"https://alexnormand-dino-ipsum.p.rapidapi.com/", params=params,
 headers={
   "X-RapidAPI-Host": "alexnormand-dino-ipsum.p.rapidapi.com",
   "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
 }
)

print (type(response.json()))
print(response.json())
>>> <class 'list'>
>>> [['Olorotitan', 'Megadactylus', 'Atlantosaurus', 'Angolatitan', 'Sinosauropteryx', 'Camptonotus', 'Protarchaeopteryx', 'Unescoceratops', 'Shanag', 'Archaeoceratops']]

Note that this time we did not specify the query parameters in the URL, but in the params argument of the requests.get function. Such a parameter transfer format is even more preferable.

How to Start Using an API with Python

Having dealt with the nuances of working with API in Python, we can create a step-by-step guide:

1. Get an API key


An API Key is (usually) a unique string of letters and numbers. In order to start working with most APIs – you must register and get an API key. You will need to add an API key to each request so that the API can identify you. On the example of RapidAPI – you can choose the method of registration that will be convenient for you. This can be a username, email, and password: Google, Facebook, or Github account.

2. Test API Endpoints with Python


Once we got the API key, we can refer to the API endpoints (according to the documentation) to check if everything is working as we expected. If we work with RapidAPI immediately after registering at the service, we can go to the section of needed API, subscribe to it if necessary, and test the answers of the endpoints we need directly on the API page. Next, we can generate a Python snippet that implements the functionality that we have just tested and quickly check it using IPython or simply insert it into our Python app.

3. Make your first Python app with API


After we checked the endpoints and everything works as we expected, we can start creating the application, including calls to the necessary API. As we already mentioned, RapidAPI will help us here. On the page of the API we need, we can use Code Snippet block and get Python snippet with access to the necessary endpoint. We just need to remember that if we use Python 3, we need to replace the unirest library with requests in the snippet code.

Get Started Now

Python API Example: Earth view app with NASA API

Having in our hands the powerful features of Python and access to a wide range of APIs, we can do something great, such as exploring the depths of space or looking at Earth from orbit for a start. For such tasks, we will need NASA API, which is available through RapidAPI.

1. Get an API key

The NASA API is free, in the basic case, it does not require a special subscription. However, with intensive use of the API, you should sign up for a NASA developer key. We are not going to use it intensively, so immediately after registering with the RapidAPI service we will receive a service key and this will be enough for us. You can register by clicking on the Sign Up button in the RapidAPI menu.

As we already mentioned, you can register in any convenient way:

2. Test API Endpoints with Python

After registration, go to the NASA API page. Enter its name in the search box at the RapidAPI service or go to the “Science” category from “All Categories” list and select this API from the list.

We are interested in the getEPICEarthImagery endpoint, which gives a list of Earth pictures names taken by NASA’s EPIC camera onboard the NOAA DSCOVR spacecraft. By default, it gives the most recent photos. If you wish, you can also specify the date of photos in the date parameter. We need fresh photos, so the default conditions suit us.

With the help of the Code Snippet block, we get the code we need. Since we use Python 3, we need to replace unirest library in the snippet with requests. So here’s our final snippet:

response = unirest.post("https://NasaAPIdimasV1.p.rapidapi.com/getEPICEarthImagery",
  headers={
    "X-RapidAPI-Host": "NasaAPIdimasV1.p.rapidapi.com",
    "X-RapidAPI-Key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/x-www-form-urlencoded"
  }
)

The response.json() method returns a Python dictionary with a list of the names and properties of the photos. Apparently, everything works well and we can start writing our application.
Make your first app with API

With the help of data with images of the Earth, we can create our own small application that will generate an animated image of the Earth based on the latest photos from NASA.

We will need the skimage library to resize images, as well as imageio to generate a single animated gif based on a selection of images. We can install them using the command:

pip3 install scikit-image imageio

We will also need the regex library to create separate variables with information about the year, month, day of the photo from the full date string. We will need these variables to form the url of an Earth photo in the format: https://epic.gsfc.nasa.gov/archive/natural/{year}/{month}/{day}/png/{image_name}.png .

As a result, we get the following application:

import requests
import re
import imageio
from skimage import transform,io

# get json with information (including name and date) about Earth pictures
response = requests.post("https://NasaAPIdimasV1.p.rapidapi.com/getEPICEarthImagery",
 headers={
   "X-RapidAPI-Host": "NasaAPIdimasV1.p.rapidapi.com",
   "X-RapidAPI-Key": "4xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
   "Content-Type": "application/x-www-form-urlencoded"
 }
)

# convert json to Python object 
data = response.json()

# create regex pattern to get separately year, month and day of an image
dates_pattern = r"^(?P<year>d{4})-(?P<month>d{2})-(?P<day>d{2})"

# download images and save each to ./images folder
for img in data['contextWrites']['to']:
   # get year, month and day with regex to create image url
   matches = re.search(dates_pattern, img['date'])
   year = matches.group('year')
   month = matches.group('month')
   day = matches.group('day')
   image_name = img['image']
   img_url = f'https://epic.gsfc.nasa.gov/archive/natural/{year}/{month}/{day}/png/{image_name}.png'
   # save image to ./images folder
   img_data = requests.get(img_url).content
   with open(f'images/{image_name}.png', 'wb') as handler:
       handler.write(img_data)

index = range(len(data['contextWrites']['to']))
images = []

# resize images and create gif from them
for i in index:
   img_name = data["contextWrites"]["to"][i]["image"]   
   img = io.imread(f'images/{img_name}.png')
   small_img = transform.resize(img, (500, 500), mode='symmetric', preserve_range=True)
   images.append(small_img)
imageio.mimsave('images/earth500.gif', images)

We obtained such an image of the Earth from orbit. A good starting point for further space exploration.

Browse the Best Free APIs List

Conclusion

In this article, we started using the REST API in Python and consistently walked through all the necessary steps to create a Python application that uses almost limitless opportunities of APIs.

Related Links

Python API Tutorials

Video Tutorials

4.9/5 - (10 votes)

View Comments

  • Nasa API is not available on rapidapi.com and it is disappointing. How can I learn using python with API if NasaAPI doesnt exist? And the document seems to have been updated on 14th September. If you can have a look at this issue and fix it, that will be great. Thank you.

Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

3 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

3 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

1 month ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago