So from the last post we have all our code in place for our F1 api, now we are looking at the following:
- Retrieving Status codes
- Filtering our query
Status code
What are status code? And why are they important?
Status codes tell us whether a HTTP request was successful or not. So there are 5 classes in which these response are categorized.
- Informational: 1XX
- Successful: 2XX
- Redirect: 3XX
- Client Error: 4XX
- Server Error:5XX
I have explained this in depth in HTTP post for more info. Now I am running the the server for my F1 website, and I want to get the status of the request I made. Following code shows how to do this.
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import requests
>>> url = ‘http://192.168.43.135:8000/laps/’
>>> response = requests.get(url)
>>> print(response.status_code)
200
The request has succeeded.
Filtering
The response variable is of type <class ‘requests.models.Response’> we convert it to either json or xml. On typing reponse.json() data is converted into<type ‘list’> and as we all know we can iterate thru a list. Following is an example of how to go forward with this:
import requests url = 'http://192.168.43.135:8000/laps/' response = requests.get(url) racer_data = response.json() for racer in racer_data: if racer['driver_name'] == 'Nino Farina': print(racer) {u'car_model': u'ALFA ROMEO', u'grand_prix': u'Great Britain', u'driver_name': u'Nino Farina', u'id': 8, u'time_taken': u'1:50.600'}
On iterating thru the list we have a condition, if the condition is true we print the enter racer’s record.
Also there is another way to filter data, we need to define a list of dict called filter. This dict will have 3 component name of the field, operation{eq, like,==}, and val. Following is a code snippet to implement this.
import requests import json url = 'http://192.168.43.135:8000/laps/' headers = {'Content-Type': 'application/json'} filters = [dict(name='car_model', op='like', val='ALFA ROMEO')] params = dict(q=json.dumps(dict(filters=filters))) response = requests.get(url, params=params, headers=headers) assert response.status_code == 200 print(response.json()) {u'car_model': u'ALFA ROMEO', u'grand_prix': u'Great Britain', u'driver_name': u'Nino Farina', u'id': 8, u'time_taken': u'1:50.600'}