Python API Requests- A Beginners Guide On API Python 2022

Spread the love

An API or Application Programming Interface is a connection between computers or computer programs. API helps two different computers to communicate and exchange data with each other. In Python, there are several HTTP libraries available to make API calls. In this tutorial, we will discuss Python API “requests” library. The other libraries available are urllib and httplib. Python “requests” library is the most simplest and elegant.

Python API - API Python
API Python

What Is HTTP?

HTTP or Hyper Text Transmission Protocol is a set of protocols designed to enable communication between clients and servers. It works as a request-response protocol between a client and server.
A web browser is a client, and an application on a computer that hosts a website is the server. So, to request a response from the server, there are mainly two methods:

GET : to request data from the server.
POST : to submit data to be processed to the server.

How To Install Python API Requests Library?

To download and install Requests library, use following command:

pip install requests

OR, download it from here and install manually.

Get Method In Python API Requests Module

A simple API requests to get current IP address.

# importing the requests library
import requests

# api-endpoint
URL = "https://api.ipify.org/?format=json"

# sending get request and saving the response as response object
r = requests.get(url = URL)

# extracting data in json format
data = r.json()

# extract the ip address from the dictionary
IP_Address = data['ip']
print(IP_Address)
Output-
122.162.147.98

In the above example, a simple API call is used to get your current IP address. In most cases, the results obtained from a API requests are in the form of JSON/ key value pairs/ dictionary type.

All APIs are not free to use and requires several parameters to be passed for example, API access token key, authorization key, etc. To provide these parameters in the requests, we can use the following approach.

# PARAMS - parameters, for example
PARAMS = {'TOKEN':'CXGHT12345_IH67'}

r = requests.get(url = URL, params = PARAMS)

Post Method In Python API Requests Module

In this example, we will learn how to paste your source_code/text to pastebin.com by sending POST request to the PASTEBIN API using Python API.
First of all, you will need to generate an API key by signing up here and then access your API key here.

# importing the requests library
import requests
  
# defining the api-endpoint 
API_ENDPOINT = "https://pastebin.com/api/api_post.php"
  
# your API key here
API_KEY = "s7DM-PPVaovN1D5eEunowjOp7d2FwLIU"
  
# your source code here
source_code = '''
print("Hello, world!")
a = 1
b = 2
print(a + b)
'''
  
# data to be sent to api
params = {'api_dev_key':API_KEY,
        'api_option':'paste',
        'api_paste_code':source_code,
         'api_paste_format':'python'}
  
# sending post request and saving response as response object
r = requests.post(url = API_ENDPOINT, data = params)
  
# extracting response text 
pastebin_url = r.text
print("The pastebin URL is: %s"%pastebin_url)
Output-
The pastebin URL is: https://pastebin.com/DcSS02hB

In response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.text.

Interested in learning more about Python, read How To Create Or Run Python Flask App Online Using Ngrok?

Common Error Codes Or Status Codes

Status codes in Python API or using any method are returned with every request that is made to a web server. Status codes indicate information about what happened with a request. Here are some codes that are relevant to GET requests:

  • 200: Everything went okay, and the result has been returned (if any).
  • 301: The server is redirecting you to a different endpoint. This can happen when a company switches domain names, or an endpoint name is changed.
  • 400: The server thinks you made a bad request. This can happen when you don’t send along the right data, among other things.
  • 401: The server thinks you’re not authenticated. Many APIs require login credentials, so this happens when you don’t send the right credentials to access an API.
  • 403: The resource you’re trying to access is forbidden: you don’t have the right to see it.
  • 404: The resource you tried to access wasn’t found on the server.
  • 503: The server is not ready to handle the request.

One can easily notice that all of the status codes that begin with a ‘4’ indicate some sort of error. The first number of status codes indicate their categorization. This is useful — you can know that if your status code starts with a ‘2’ it was successful and if it starts with a ‘4’ or ‘5’ there was an error. If you’re interested you can read more about status codes here.

Points To Remember

  • All form data is encoded into the URL, appended to the action URL as query string parameters in GET method while in POST, form data appears within the message body of the HTTP request.
  • Only ASCII characters are allowed for data to be sent in GET method. There is no such restriction in POST method.
  • GET is less secure compared to POST because data sent is part of the URL. So, GET method should not be used while sending passwords or other sensitive information.

Interested in more informative articles, read How To Create A Chatbot In Python Using NLP (NLTK)?

Summary

In this article, we discussed Python API requests library using examples. In the GET method, we use API call to get our current IP address. While in POST method, we use pastebin to paste a source code in it. We also discussed some common status codes while working with APIs.

Please support our effort by commenting below. Feel free to contact us in case of any queries.


Spread the love

Related Posts

This Post Has One Comment

Leave a Reply

Your email address will not be published.

© 2022 Pykit - All Rights Reserved!