0

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?

4
  • 2
    What is print(response.status)? Commented Sep 20, 2021 at 8:29
  • @AbdulNiyasPM It showed success, but how can I print token instead of success ? Commented Sep 20, 2021 at 8:30
  • 2
    Try to read the response body response.read() Commented Sep 20, 2021 at 8:31
  • @AbdulNiyasPM ahh i see, now it able to show me the token and other values. Thanks bro Commented Sep 20, 2021 at 8:32

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. But how can i use urllib as GET request? Does it the same if i use req = urllib.request.Request(myurl) ?
@terry5546 urllib.request.Request also accept an argument called method which lets you to specify the method. If you don't specify anything the default value is GET
0

you can simply just use requests:

import requests

headers = {
    'Content-Type': 'application/json',
}

data = '{\n"email": "[email protected]",\n"password": "PASSWORD"\n}'

response = requests.post('https://xx.com/login', headers=headers, data=data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.