Home > Software design >  I am trying to access the api with cookie in python but it fails on GET request
I am trying to access the api with cookie in python but it fails on GET request

Time:07-07

I am trying to access the api with cookie in python and the code gets the cookies from the api on http POST request but it fails on the second attent on http GET request and fails to use the cookie. I want the code to get the cookies from the HTTP POST request and utilies it on the GET HTTP request . I have been struggling for week please me out with the code.

import requests

s= requests.Session()

url = "https://api.ommasign.com/v1/users/apikey/login?token=xxxxxx"

r = requests.post(url)
c1 = r.cookies
c1 = str(r.cookies).replace("<RequestsCookieJar[<","").replace("for .api.ommasign.com/>]>","").replace("Cookie","").strip()

print(c1)
c2 = r.json()
print(c2)



url1 = "https://api.ommasign.com/v1/devices?token=xxxxxx&status=offline"
payload={}
headers = {
  'Cookies': c1
}
print(headers)
response = requests.request("GET", url1, headers=headers, data=payload)
result =response.json()
# result1 = str(result['count'])
print(result)

print("Done")

This is the JSON result i get

{'id': 1710, 'name': 'OMMA API', 'email': '[email protected]'}
{'Cookies': 'connect.sid=s:1PmUTVMmJbzS88SN3LcGL7Kc2gw5sVg5.P0Uhb+qA87QKQHDp26IsVj23I8r6XHAVQmTDh4ghhkM'}
{'error': 'Not authorized.', 'payload': {'isCaptchaRequired': False}, 'now': 1657153596984}
Done

CodePudding user response:

Use the Session object to make the requests, the cookies will persist on the session

import requests

s = requests.Session()

s.post("https://api.ommasign.com/v1/users/apikey/login?token=xxxxxxx")

response = s.get("https://api.ommasign.com/v1/devices?token=xxxxxxx&status=offline")
result = response.json()
print(result)
  • Related