Vinod K
Vinod K

Reputation: 2123

Python Script to send JSON request using the Cookies of the website

I am trying to imitate a authenticated JSON request. I am using the Requests module to do so.

import requests
import json

url = "https://"
headers = {
    'Host': 'example.com',
    'content-type': 'application/json',
    'Connection': 'keep-alive'
}

data = {
"asdsdsd": {
    "AppName": "esdf",
    "Language": "EN",
    "fsef": [
        {
            "sfddf": [
                {
                    "sdfsdfsdf": "sdfsdfsdf"
                }
            ]
        }
    ]
},
"sdfdf": {
    "sdfsdf": "sdfsdfsdf"
}
}

r = requests.post(url, data=json.dumps(data), headers=headers ,verify=False)

How do i include the authenticated cookie into this.

Can I open this request using a browser(with the headers & data) then i would be able to use the authenticated cookie of the browser.

Is there any way to do this ?

Upvotes: 0

Views: 3305

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121336

Use a Session object to manage cookies.

s = requests.Session()

# load initial page to get session cookies set, perhaps a CSRF token
loginform = s.get(loginurl)

# post login information to the form
s.post(someurl, data={...})

# post JSON with session with authentication cookie
s.post(someurl, ...)

Upvotes: 1

Depado
Depado

Reputation: 4929

You can pass your data directly into the form of a cookie in your request like this :

data = {
    "sessionid":"yoursessionidorsomethingelseidontcarelolwtfhelloworld"
}
url = "https://youramazingurl.com/list_some_private_data"
res = requests.get(url, cookies=data)

Done :)

Upvotes: 0

MONTYHS
MONTYHS

Reputation: 924

headers = {
'Host': 'example.com',
'content-type': 'application/json',
'Connection': 'keep-alive'
}

session = requests.session()
session.headers=headers

you can use session for post

session.post(url, data=json.dumps(data) ,verify=False)

Upvotes: 0

Related Questions