Как создавать API-запросы в Python (используем Requests и aio

Api wrappers

With respect to Python, API wrappers are essentially libraries/packages which can be installed using pip. These libraries help communicate with APIs in a syntactically cleaner way. Under the hood, the libraries still make use of requests and headers to make requests. However, the wrappers make your code look cleaner.

The Twilio API we discussed earlier has a wrapper. It can be installed using pip

pip install twilio

Let’s try to do the same thing we did in the previous section with Twilio

from twilio.rest import Client
from dotenv import load_dotenv
import os
load_dotenv()
TWILIO_ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID")
TWILIO_ACCOUNT_TOKEN = os.environ.get("TWILIO_ACCOUNT_TOKEN")
client = Client(TWILIO_ACCOUNT_SID , TWILIO_ACCOUNT_TOKEN)
calls = client.calls.list(limit=5)
for idx, record in enumerate(calls): print(f"{idx}. {record.duration}")

As you can see, the code is a few lines shorter and looks much cleaner.

Unfortunately, not all APIs have a wrapper. However, a lot of them do. Before a consumer, an API directly, try searching for a wrapper around it. This will make it significantly easier to work with the API.

Apis with keys

This is the most common form of authentication when consuming APIs. The API Key/Token is passed in as a header while making the request. We will be working with the Cat as a Service (CAAS) API. You can get a key here

In this article, we will be working with 5 different apis which use different types of authentication. we will be using python to consume the apis.

Not all APIs are as well documented as Twilio. This guide should help you work with APIs which are secured using Keys, BasicAuth, or OAuth2.

We will be working with the following APIS

You can find the source code here

Insecure apis

The Cat Facts API does not require any authentication and is fairly straightforward to work with. Let’s make a request to the following endpoint

Python requests certificate verify failed

If you get the python requests ssl certificate_verify_failed error, the cause is that the certificate may be expired, revoked, or not trusted by you as the caller. If you are in a test environment then it may be safe to set verify=False on your call, as explained above.

Python requests ignore ssl

To ignore SSL verification of the installed X.509 SSL certificate, set verify=False. For example, in a python requests GET request to ignore ssl:

Reading from .env files

Before moving on to the next sections, let’s look at how to read variables from a .env file. It’s highly recommended to store your credentials in a .env file to avoid them being exposed to others.

We will need to install the python-dotenv library.

pip install python-dotenv

Assume have a .env file with some random API Token

API_TOKEN = "SOME API TOKEN"

Let’s try reading the API Token in Python.

from dotenv import load_dotenv
import os
load_dotenv()
API_TOKEN = os.environ.get("API_TOKEN")

The get function accepts a variable name stored in the .env file as an argument.

Resources

Github Repo

Table of contents

  • Insecure APIs
  • Reading values from.env files
  • APIs with Keys
  • APIs with Basic Auth
  • API Wrappers
  • The Session Object
  • APIs secured via OAuth2
  • Using the GitHub API (OAuth2)
  • Using the Genius API (OAuth2)

Some familiarity with the requests library is expected. If you need a refresher, you can refer to my previous article.

Using the genius api (oauth2)

Let’s take a look at another example. I’ll skip the part where we import the libraries and load the credentials.

Некоторые дополнительные библиотеки

Хотя библиотека Requests и является самой популярной и универсальной, в некоторых особых случаях вы можете найти полезными и другие библиотеки.

Распространенные типы api-запросов в библиотеке requests

Наиболее простой GET-запрос интуитивно понятен:

Conclusion

I hope this article serves as a good guide to work with APIs in Python. Before consuming an API directly, always look for a wrapper. The 5 mins you spend looking for a wrapper might save you hours of headache.

Похожее:  Sigen pro кошелек - подробная инструкция пользования