How to Extract REST API Data using Python

by Aug 14, 2022IoT Programming

Introduction

In this tutorial, we will be discussing in detail on how to extract REST API data using Python. It is one of the most popular APIs and is used by a majority of applications. We will be using VS code editor for executing the python code. The extracted API data would be in a CSV or text file format.

Now, let us look at what we mean by a REST API.

What is a REST API?

So let’s get started with the basics – what is an API? The term API stands for Application Programming Interface. They are basically mechanisms that enable two software components to communicate with each other using pre-defined protocols. This communication is facilitated by means of requests and responses.

Speaking of the architecture of APIs, there is a client-side as well as a server-side. The application that sends the request is called the client while the application that sends the response is called the server. There are several ways in which an API works. One such way is REST API.

A RESTful API (also known as REST API) is one of the most flexible and popular APIs at present. The term REST stands for Representational State Transfer. It is a set of architectural constraints (not a protocol or standard). When a request is made via REST API, a representation of the state of the resource is sent by it to the requester. This representation could be in several formats such as JSON, HTML, Python, plain text, etc.

Source: Codeacademy

Extracting REST API using Python

Selecting an API

The first step is to select a free API. Search rapid API in Google. Click on the first link as shown below.

Note that we are not promoting any API here, we are just using one for demonstration purposes. Also note that in order to get the API Key, we need to create an account on the platform.

Next, scroll down the page and click on the option shown below.

Next, search for currency scoop in the search bar as shown below:

Subsequently, you will be able to see a section for an API key and Host details. Note that the API key will be visible only after signing in to your account

Now, let’s get to the coding part.

Python code for extracting REST API data

Importing modules

Here, we will be looking at the code part-by-part for better understanding. The first part of the coding involves importing some modules as shown below:

import requests
import pandas as pd
import json

The modules that we would need are requests, pandas, and json. The requests module is used to send HTTP requests using Python. This module is essential for connecting with the internet and extracting the data from the URL. Following this, we import the Pandas module which is efficient for data cleaning and analysis. Next, we import the json module which allows us to work with data in JSON format.

NOTE: The requests module and pandas module are not in-built modules, unlike the json module. You will have to install them in case you haven’t installed them.

Extracting the data

url = "https://currencyscoop.p.rapidapi.com/latest"

headers = {
	"X-RapidAPI-Key": "type-your token-here",
	"X-RapidAPI-Host": "currencyscoop.p.rapidapi.com"
}

response = requests.request("GET", url, headers=headers)
myjson = response.json()
myjson_data = myjson['response']

Next, we need to create a variable url and paste the URL given in the code. Following this, we define our headers section where we specify the API Key and the Host details. Headers represent the metadata associated with the API request and response.

Subsequently, we use the request function of the requests module. The first parameter is GET which is used to retrieve data from a server at the specified resource. The second parameter is the URL to the webpage. The third parameter is the headers.

Next, we parse the text retrieved as JSON using the response.json() function. Finally, we create another variable named myjson_data which is assigned to myjson[‘response’]. Note that this is done to get the data within the response section of the data retrieved (this is done so that when we extract data to a CSV file, it is in proper format).

Writing the data

Now, let’s look at how to write this data onto a CSV file.

#writing data in csv format

data_csv = pd.DataFrame(myjson_data)
data_csv.to_csv('currency_rates.csv')

First, we convert the data into a Pandas Dataframe. Next, we convert this to a CSV file using the .to_csv command. This result will be as follows:

TIP: In order to view the columns entirely in Excel, first select everything using Ctrl+A and then go to Format -> Autofit Column Width.

Now, let us look at how to write data to a text file.

#writing data to a text file

with open('currency_rates.txt','w') as f:
    json.dump(myjson, f, indent=4)

Now, using the with open function, we open a new text file named currency_rates.txt in write mode. Next, using the json.dump() function, we write all the data into this newly created file. The results are as follows:

Conclusion

So, we have successfully extracted REST API data using Python. We have seen how to choose an API, how to extract it, and how to write it into CSV and text formats. Hope that this tutorial was informative and worth your time!

Happy Learning!

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Advanced Generics: Higher-Order Functions

Advanced Generics: Higher-Order Functions

In our journey through TypeScript generics, we've covered the basics, interfaces, and classes. Now, it's time to explore advanced concepts by combining generics with higher-order functions. These functions, which take other functions as arguments or return them,...

Basic Usage of Generics in Typescript

Basic Usage of Generics in Typescript

Keypoints Show how to declare generic functions and classes in TypeScript. Provide examples of generic functions that work with different data types. Demonstrate the use of built-in generics like Array<T> and Promise<T>. Here's the content...

Getting Started with Bash Script : A Simple Guide

Getting Started with Bash Script : A Simple Guide

Introduction In this tutorial, we will be looking into Bash Script - a tool used by developers to increase productivity and manage tasks. A lot of professionals use it for tasks such as system administration, data crunching, web app development, automated backups,...

Create a Simple ReactJs Application – Part 1

Create a Simple ReactJs Application – Part 1

ReactJs is one of the famous front-end open-source libraries of JavaScript developed by Facebook. It aims to allow developers to quickly create fast user interfaces for websites and applications. In this blog, we will create a simple and basic ReactJs...

Create a Simple ReactJs Application – Part 2

Create a Simple ReactJs Application – Part 2

In the tutorial's last part, we discussed about ReactJs and how to run a simple react app on a web browser. In this part, we will dig more into some interesting stuff, such as creating a home, about us, and contact pages. Click here for the first part - Create a...

Basic MATLAB Commands and its Functionality

Basic MATLAB Commands and its Functionality

MATLAB is a language used by engineers and scientists for computational mathematics. It is used for developing algorithms, analyzing them, and also for creating models and applications. MATLAB also helps in developing applications using by deploying applications,...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....