How these 2 python libraries are making our lives easier
If you are working on an application that deals with APIs, knowing how to handle HTTP Requests and JSON content is crucial. These two Python libraries come in handy in such scenarios.
Requests
requests
library gives you a simple interface to make HTTP calls to APIs. It is one of the most popular in this domain and is very easy to use.
It does all the HTTP actions that your browser can do, like making a GET request to fetch some data or POST requests for creating new entries among many more things.
You can easily install this with pip.
pip install requests
And start using it like it right away:
- GET Request example
import requestsr = requests.get('https://example.com/api')
print(r.json())
- POST Request example
api_url = 'https://www.example.com/api'
data_to_send = {'somekey': 'somevalue'}
response = requests.post(api_url, data = data_to_send)
#json can also be used instead of data above
print(response.text)
These are some of the very basic functionality of the requests library and a lot of customization can be done here in terms of headers like content-type
, authentication, cookies, proxies, timeouts, and so on.
JSON
json
is one of the most widely used libraries while dealing with JSON data and files. A lot of HTTP request and response cycle works on JSON data and this really helps with all that.
json
provides you with 4 basic functions with which you can do pretty much everything. These are dump
, dumps
, load
, loads
Let's go through them:
- Dumps and Dump
dumps
will convert a python object like dict
, list
, etc to a JSON object. A simple use case might be to send this JSON as API response.
import json data = {
"id": "123",
"name": "John Doe",
"occupation": "Farmer"
} json_object = json.dumps(data, indent = 4)
print(json_object)
But you’ll be using dump when you want to convert a python object and store it in a JSON file in the local system. Here’s how it’s done:
import jsondata = {
"id": "123",
"name": "John Doe",
"occupation": "Farmer"
}with open("output_file.json", "w") as file:
json.dump(data, file)
- Load and Loads
Similarly, for load
and loads
are used while reading the JSON, either from a JSON file or from a JSON object.
import jsonjson_object_string = """{
"id": "123",
"name": "John Doe",
"occupation": "Farmer"
}
"""data_dict = json.loads(json_object_string)
print(data_dict)
Reading from a file:
import jsonwith open("sample_data.json", "r") as file:
data = json.load(read_file)
print(data)
You’ll probably end up using these two libraries together. But they are very much useful by themselves. I’d like to cover more content like this if I get a good response.
Until then, follow for more new and exciting stuff. And if you’d like to, join CodeByte’s discord server here.