Home > Enterprise >  How to curl in Python with header, data?
How to curl in Python with header, data?

Time:09-22

I'm trying replace the following curl command by a Python script:

curl --request POST \
 --url https://xx.com/login \
 --header 'Content-Type: application/json' \
 --data '{
"email": "[email protected]",
"password": "PASSWORD"
}'

Script that I tried:

import urllib.request
import json

body = {"email": "[email protected]","password": "xxx"}
myurl = "https://xx.com/login"

req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)

When I tried to run this script, it doesn't return me anything and show processed completed. Is my code logic correct? Or there is something wrong with my code?

CodePudding user response:

For HTTP and HTTPS URLs, urllib.request.urlopen function returns a http.client.HTTPResponse object. It has different attributes and methods you can use, For example,

HTTPResponse.read([amt]) - Reads and returns the response body, or up to the next amt bytes.

HTTPResponse.getheaders() - Return a list of (header, value) tuples.

HTTPResponse.status - Status code returned by server.

So in your case you could do check the status using status attribute . If it's successful read the response body using read method.

status_code = response.status
if status_code == 200: # request succeeded
    response_body = response.read() # This will be byte object
    response_body_as_string = response_body.decode('utf-8')
  • Related