简体   繁体   中英

translating simple curl call to python/django request

I'm attempting to translate the following curl request to something that will run in django.

curl -X POST https://api.lemlist.com/api/hooks --data '{"targetUrl":"https://example.com/lemlist-hook"}' --header "Content-Type: application/json" --user ":1234567980abcedf"

I've run this in git bash and it returns the expected response.

What I have in my django project is the following:

        apikey = '1234567980abcedf'
        hookurl = 'https://example.com/lemlist-hook'
        data = '{"targetUrl":hookurl}'

        headers = {'Content-Type': 'application/json'}
        response = requests.post(f'https://api.lemlist.com/api/hooks/', data=data, headers=headers, auth=('', apikey))

Running this python code returns this as a json response

{}

Any thoughts on where there might be a problem in my code?

Thanks!

Adding to what nikoola said, I think you want that whole data line to be as follows so you aren't passing that whole thing as a string. Requests will handle serializing and converting python objects to json for you [EDIT: if you use the json argument instead of data].

source: https://requests.readthedocs.io/en/master/user/quickstart/#more-complicated-post-requests

Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:

Note, the json parameter is ignored if either data or files is passed.

Using the json parameter in the request will change the Content-Type in the header to application/json.

data = {"targetUrl":hookurl}

import requests

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

data = '{"targetUrl":"https://example.com/lemlist-hook"}'

response = requests.post('https://api.lemlist.com/api/hooks', headers=headers, data=data, auth=('', '1234567980abcedf'))

You can visit this url:- https://curl.trillworks.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM