Using standard libraries for RESTful APIs

In this section, we are going to learn how to use RESTful APIs. To do this, we are going to use the requests and JSON modules of Python. We will see an example now. First, we are going to use the requests module to get the information from an API. We will see GET and POST requests.

First, you must install the requests library as follows:

            $ pip3 install requests

Now, we will see an example. Create a rest_get_example.py script and write the following content in it:

import requests

req_obj = requests.get('https://www.imdb.com/news/top?ref_=nv_tp_nw')
print(req_obj)

Run the script and you will get the output as follows:

student@ubuntu:~/work$ python3 rest_get_example.py
Output:
<Response [200]>

In the preceding example, we imported the requests module to get the request. Next, we created a request object, req_obj, and specified a link from where we want to get the request. And next, we printed it. The output we got is a status code 200, which indicates success.

Now, we are going to see the POST request example. POST requests are used for sending data to a server. Create a rest_post_example.py script and write the following content in it:

import requests
import json

url_name = 'http://httpbin.org/post'
data = {"Name" : "John"}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}
response = requests.post(url_name, data=data_json, headers=headers)
print(response)

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 rest_post_example.py
Output:
<Response [200]>

In the preceding example, we learned about the POST request. First, we imported the necessary module requests and JSON. Next, we mentioned the URL. Also, we entered the data that we want to post in a dictionary format. Next, we mentioned headers. And then we posted, using a POST request. The output we got is status code 200, which is a success code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset