Case 2 – demonstrating status codes and informative responses from the API

In this section, we will be using the following URLhttps://api.twitter.com/1.1/search/tweets.json?q=.

In this section, we will be processing an API request from Twitter. The URL to be requested is https://api.twitter.com/1.1/search/tweets.json?q=. By using this URL, we can easily identify that the query string, q, is empty, and that the value that's expected by the Twitter API is not provided. The complete URL should have been something along the lines of https://api.twitter.com/1.1/search/tweets.json?q=nasa&result_type=popular.

The response that was returned was for an incomplete API call, and can be seen in the following screenshot, along with the HTTP status code (400 or Bad Request) and a message that was returned by the API stating errors with "message" : "Bad Authentication data"For more information on the Twitter API's Search option, please refer to https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets:

Incomplete request made to Twitter API

The response that was returned by Twitter API is actually information, not an error. Such informative responses make the API more scalable and easy to debug when they're used by other resources. It's also an appreciated characteristic of RESTful web services. This kind of information can be easily overcome by deploying API parameters and other requirements. 

The following code will make a request to Twitter with an empty query string and identify the responses:

import requests
import json
url = 'https://api.twitter.com/1.1/search/tweets.json?q='

results = requests.get(url)
print("Status Code: ", results.status_code)
print("Headers: Content-Type: ", results.headers['Content-Type'])

jsonResult = results.content #jsonResult = results.json()
print(jsonResult)

jsonFinal = json.loads(jsonResult.decode())
print(jsonFinal) #print(json.loads(requests.get(url).content.decode()))

if results.status_code==400:
print(jsonFinal['errors'][0]['message'])
else:
pass

The preceding code uses the json Python library to load the decoded jsonResult that was obtained by using the loads() function. We can also use json() from requests, as we did in case 1. jsonFinal is now a Python dictionary object and can be explored so that we can find its 'key:value'. The final output is as follows:

Status Code: 400
Headers: Content-Type: application/json; charset=utf-8

b'{"errors":[{"code":215,"message":"Bad Authentication data."}]}'
{'errors': [{'message': 'Bad Authentication data.', 'code': 215}]}

Bad Authentication data.
..................Content has been hidden....................

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