How to Send a Web API Request in Python

In this post we’ll cover how to send an API request to a web API in Python. Web APIs are all the rage nowadays. The advantages of using a web API over a library include not having to install and configure a library, having much of the code abstracted out for you, and, in the case of machine learning, not having to handle the models.

Here’s an extension on How to Send Web API Requests Asynchronously.

Setting up an API Request

The web API that we’ll use for our example is the Text API. To get an API key, simply go to the site, create an account, and you should see your API key just like the image below. I’ve blurred out my API key for obvious reasons.

API Key location in The Text API
API Key location in The Text API

As always, we’ll start with the libraries that we’ll need. The simplest way to make an API request in Python is to use the “requests” library. This library is native to Python so we won’t need to install anything. I will also import a config file. This is best practice for using API keys, but you may choose to keep your API key in the file itself if you wish.

import requests
from text_api_config import apikey

After we import our libraries and API key, we’ll need to define the URL, create the headers, and create the body. We’ll be sending our request in JSON format. For this use case, I’ve ripped one of the paragraphs from the post about sending emails with attachments using Python. In the headers you’ll see that I’ve included a “Content-Type” key which tells the server to expect content in the form of a JSON. I’ve also included an “api-key” key which will be used to authorize our request.

Create an API Request

url = "https://www.thetextapi.com/text/summarize"
 
headers = {
    "Content-Type": "application/json",
    "api-key": apikey
}
 
text = """Here’s where we’ll switch things up before we send out the email. We’ll use os.path.basename to find the name of the file. This command will extract the basename of the file from the passed in filename (that is the name without the directory extensions). We’ll open the file to read in as bytes, and use our MIMEApplication object to read in our file. Make sure to specify your file type using the “_subtype” parameter. Ours will be a “txt” file. Then close our file to prevent memory leaks. Once we’ve created our attachment object, we need to add a header to it to let the MIMEMultipart object know what we’re attaching. Finally, we simply call the MIMEMultipart object, “message”, and attach our attachment object before we call the server to send the mail."""
 
body = {
    "text": text
}

Call the API

Note that the “body” of our request is specific to this API format and you may have to change the body of your request if you are sending your request to another API endpoint. Once we’ve declared all of our variables that we need to send a request, we’ll send a post request using the requests library as shown below. Note that not all responses will have a “.text” attribute, but this one does. You may have to do some fiddling around and debugging your response format before you can confidently pick an attribute to display.

response = requests.post(url, headers=headers, json=body)
print(response.text)

We run this program simply by calling

python <program name>

The output should look like the following:

Response from API

Further Reading

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly
Yujian Tang

3 thoughts on “How to Send a Web API Request in Python

Leave a Reply

%d bloggers like this: