- API Integration in Python
- REST API
- REST Client
- Code Snippet
- Client Libraries
- SDKs
- How to Integrate an API in Python with Requests
- Prerequisites
- Create Basic Flask App
- Integrate API in Python Using Requests
- Create a Paw Cloud Project
- API Cloud Sync
- Testing Python REST API Locally
- Code Preview
- Conclusion
- FAQs
- How to Use Python Requests with REST APIs?
- Why use an API instead of a static dataset you can download?
- What are common HTTP request libraries in Python?
- Footnotes
API Integration in Python
APIs (Application Programming Interface) can be an incredible tool for developers and applications. Internal APIs can help keep features, servers, and data modular so teams can iterate on disparate services without breaking everything. External APIs can provide data and services that are either unavailable to your organization or take an incredible amount of time to develop in-house.
Conversely, APIs may be the backend for the web application. Regardless, APIs are common in software development because of how much they can help. With the popularity of APIs, we often find ourselves needing to integrate APIs in our applications and source code.
The most important tool for API development, integration, and testing is an API client. In this article, we’ll look at how you can use a RESTful API client with Python.
REST API
This article will not go deep into answering the question, what is a RESTful API? You can follow the link for a longer definition. Although, I will briefly list a few characteristics of REST APIs.
REST APIs are the most common on the internet and follow the RESTful architecture, which includes 1 :
- Uniform interface: This includes commons naming protocols, consistent retrievable patterns (HTTP methods like GET, PUT, PATCH), and single-URI resource identification.
- Client-server separation: The client applications and servers can evolve separately from each other.
- Stateless: The client context between API calls is not stored, so every request is evaluated as new and not contingent on prior requests.
There are more architectural constraints, but those are a few of the main ones.
Next, you may have noticed the term client appear multiple times in this section. We’ll briefly discuss the relationship between REST clients, client libraries, SDKs, and code snippets in the next couple of sections. If you’re familiar with these topics, I suggest you skip down to the tutorial.
REST Client
Servers hold files of data and typically serve that data to clients. In a REST context, the server and clients use the HTTP protocol to mediate data transfer between the two entities. HTTP is a standardized protocol. So, clients’ communication to the server does not depend on the type of application or the programming language it’s written in because HTTP is the medium.
Therefore, API clients are popular with developers because they allow them to perform API testing (as well as document, mock, etc.) that does not depend on a specific programming language. Other terms to describe API clients are HTTP client, REST client, or API testing tool.
Unfortunately, these terms often overlap, and it can get confusing if you’re new to the terminology. Remember, a REST client communicates with a server through an API and can be a client application or API tool.
Code Snippet
API clients offer a variety of features. These features can include automatically generating API documentation, tests, mock servers, and code.
Below is an automatically generated code snippet for calling an API route from a client application built with Python.
Additionally, the code snippet generation can take into account parameters, headers, and authorization. It’s a useful service, and we’ll explore it more in the tutorial.
Client Libraries
Each client accessing an API can be different, despite the shared use of HTTP requests. Therefore, developers utilizing a certain language in their client application (i.e., Javascript or Python) look for the client libraries written in the language.
For example, users hoping to access their AWS resources through the API using Python often download and use the boto3 library. Client libraries built for accessing an API in a specific programming language can help format the request body, set the correct authorization header, handle errors, and build the correct URL.
Also, these libraries are built on top of the standard programming language-specific libraries capable of correctly forming and sending HTTP requests. For example, for Python, most generic API calls use requests, httplib2, or urllib. However, the most popular is the requests library.
SDKs
Software development kits (SDKs) are more for the context of using a platform. For example, there are vital SDKs for developing applications for Chrome Browser or with React Native (mobile). Unsurprisingly, the SDKs may contain libraries and APIs, so remember that the term is not exclusive.
In the rest of the article, we’ll look at how you can use a RESTful API client with the requests library in Python.
How to Integrate an API in Python with Requests
You don’t have to be an expert in Python to follow this tutorial, but a good understanding of basic language features will help.
The tutorial starts with setting up a basic Flask application with a couple of routes. Then, we’ll test the Flask API—on our local machine—before using Python’s request library to integrate the API with an external API (Yahoo Finance).
Finally, we’ll look at how to call our Flask API to test and retrieve code snippets.
Prerequisites
- Python programming experience
- How to open and use the command line on your OS
- Code editor (i.e., VSCode, Sublime Text, Atom, Vim)
- RapidAPI account. The tutorial uses a free third-party API on RapidAPI’s marketplace. You can sign up here.
- Paw account. The tutorial uses the Paw desktop app as an API client
Create Basic Flask App
Open up a new terminal or command prompt and navigate to where you want to add the project.
Create a new folder named rapidapi-python-requests-client
Then, execute the following command:
Next, open up a text editor or IDE (integrated development environment) and create a new file, app.py .
from flask import Flask, jsonify app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!"
Start the application on your machine by executing flask run in your terminal. Then, check the output from Flask to see where your API is running.
My application is on port 5000. So, in my browser, if I navigate to http://localhost:5000 I’ll hit our root index route (“/”).
You may notice that the environment is, by default, set to production. This is set with an environment variable in Flask. However, we will leave it as is for this tutorial. To learn more about how to change this environment variable, visit the Flask documentation.
Integrate API in Python Using Requests
Let’s add a new route to the API that calls an external API to retrieve data.
First, navigate to the Yahoo Finance API on RapidAPI.
Then, click on the Pricing tab and subscribe to the Basic (free) plan.
Back on the Endpoints tab, select the stock dropdown on the left. In the dropdown, click the route stock/v2/get-summary.
On the far right panel, click on Code Snippets, then select (Python) Requests.
In a few clicks, we can gain access and then have the code to call an external API.
RapidAPI’s marketplace provides API client tools like documentation, code generation, and mocking.
Next, copy the Python code from RapidAPI into a new route in app.py . But first, we need to make sure that the requests module is installed locally.
Then add the import to the top of the file.
# app.py import requests from flask import Flask # . @app.route('/stock/') def integrate_with_third_party(): url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-summary" querystring = headers = < 'x-rapidapi-key': "apikey", 'x-rapidapi-host': 'apidojo-yahoo-finance-v1.p.rapidapi.com' >response = requests.request("GET", url, headers=headers, params=querystring) print(response.text)
Let’s make a few changes so that the API route uses dynamic URL parameters, error handling and extracts the stock price from the request body.
# app.py import requests from flask import Flask, jsonify # . @app.route('/stock/') def integrate_with_third_party(symbol): url = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-summary" querystring = headers = < 'x-rapidapi-key': "API key", 'x-rapidapi-host': 'apidojo-yahoo-finance-v1.p.rapidapi.com' >response = requests.request("GET", url, headers=headers, params=querystring) to_json = response.json() try: price = to_json.get('price') reg_price = price.get('regularMarketPrice') except (KeyError, AttributeError): return 'No price could be found for that symbol.' return jsonify(reg_price)
We could test this new route in the browser (by entering the URL), but that becomes tedious. So instead, let’s use a REST API client to test this route locally.
Create a Paw Cloud Project
Navigate to your Paw account to view projects. Chances are, you do not have any yet. So, the next step is to download the Paw desktop app for your operating system.
On your Paw account dashboard, click the Download Paw button.
After it finishes downloading, open the application. I’m using macOS, so my interface may be slightly different from yours. However, I hope you can follow along.
Click on File in the application toolbar to create a new project.
Select New Cloud Project.
Name the project “Finance.”
After creating the project, the application takes you to the API client dashboard.
API Cloud Sync
Creating cloud projects in Paw desktop makes them available in other places. For example, back on your Paw account, refresh the page. You should see the new Finance project.
Similarly, if you visit paw.app, you’ll see your project available through RapidAPI Design by Paw‘s cloud API client.
We still don’t know if the new route works. So, we should test the route using the Paw desktop app.
Testing Python REST API Locally
Back in Paw Desktop, enter the below URL in the request URL input.
After typing in the URL, press enter to send the request. It should succeed. Furthermore, we can view the response in a raw format or JSON. Notice, we can inspect the headers or network information from the side panel, as well.
The price data may seem cryptic because it’s in JSON. However, the response tells us that Tesla’s (TSLA) price is approximately $647/share.
Code Preview
Just like in the RapidAPI marketplace, we can view and use code snippets in Paw.
Below the request description, in the Preview panel, click on the dropdown that brings up a list of programming languages—select Python (Requests).
The code is slightly different than the sample Python code on RapidAPI, but it works nonetheless. In reality, it’s probably a better code snippet because of its error handling.
Conclusion
This is only the beginning of using REST API clients in Python and building out APIs with the requests library. This tutorial set up a basic Flask API integrated with the Yahoo Finance API through RapidAPI.
Then, we created a Paw Cloud project and tested our API locally to examine the response and request data. I hope this tutorial was helpful and that it leaves you wanting to learn more about APIs, Python, and REST clients.
FAQs
How to Use Python Requests with REST APIs?
Install the requests library with pip install requests. Then, save the URL in a string. Next, pass the URL variable, and any headers to requests.request(‘GET’, url) and save the function call in a new variable. If the request was successful, you’ll be able to see the results by accessing the text property of your response variable. Alternatively, you can use API clients to generate code snippets for Python.
Why use an API instead of a static dataset you can download?
With an API, we can fetch fresh data from a server. If your dataset never changes, then a static dataset may work. Also, an application using an API can fetch the data on different systems. If you application relays on a static local dataset, you should ensure that dataset is always available.
What are common HTTP request libraries in Python?
Common HTTP request libraries in Python include requests, httplib2, or urllib.
Footnotes
1 “REST Principles and Architectural Constraints – REST API Tutorial.” Restfulapi.net, 5 June 2019, restfulapi.net/rest-architectural-constraints/.