pythonrestcurlhttplibcookiejar

Python code for REST calls with cookiejar file


I use following curl commands to fetch data using cookiejar file:

$ curl -sk -X 'POST' -d "username=name@domain.com&password=mypassword" -c app.cookie-jar -k https://website.com/auth/authenticate
$ curl -sk -X 'GET' -H 'Accept: text/csv' -b app.cookie-jar https://website.com/api/systems > out.csv

Can someone help with python script that can help in achieving the same


Solution

  • Using Requests, set up a session to keep track of the cookie:

    import requests
    
    with requests.Session() as s:
        resp = s.post('https://website.com/auth/authenticate', data='username=name@domain.com&password=mypassword')
        resp.raise_for_status()
        resp = s.get('https://website.com/api/systems', headers={'Accept': 'text/csv'})
        resp.raise_for_status()
        with open('out.csv', 'wb') as outf:
            outf.write(resp.content)