Requests Library in Python
Concept
Python requests Library is used For API testing as well as API calls within a python script.
By using the requests Library we can get a response as well as we can post, updated, delete data. This is mainly used for API calls with py script even we can use API token we can change the content type.
Code
Step 1: pip install requests
Now it is ready to use
Example 1:
res = requests.get(url=<Your URL>, headers={ 'Accept': 'application/json', ...... })
print(res.status_code) # ----- > you will be getting status code of response
print(res.text) # ------> response body
print(res.content) # ------> response body
Example 2:
res = requests.get('https://api.github.com/user', auth=('<Your Git Username>', '< Your Git Password>'))
""" You will be able to login in git by using request Lib """
print(res.headers['content-type'])
print(res.json()) # ----> print the response body
Example 3:
res = requests.post('https://httpbin.org/post', headers={ 'Accept': 'application/json',. }, data = {'key':'value'})
print(res.status_code)
Example 4:
res = requests.put('https://httpbin.org/put', data = {'key':'value'})
print(res.status_code)
Example 5:
res = requests.delete('https://httpbin.org/delete')
print(res.status_code)
Example 6:
res = requests.head('https://httpbin.org/get')
print(res.status_code)
Example 7:
res = requests.options('https://httpbin.org/get')
print(res.status_code)
Example 8:
payload = {'key1': 'value1', 'key2': 'value2'}
res = requests.get('https://httpbin.org/get', params=payload)
print(res.status_code)
Comments
Post a Comment