-1

I am trying to use a web API in my Python program, but I can't figure out how.

Here is an example call using the command line in Bash/Unix:

wget --post-file="example.txt" "http://example.com/api" -O output_filename

How would I replicate this functionality with Python's urllib module? I'm reading through the documentation for the module, but I'm not quite sure how to send a POST request to the website with a file attached. Any help or advice would be appreciated.

I found this answer to a question a few years ago that seems to be doing something along the lines of what I am trying to do, but I don't seems to be getting the desired result when I try to replicate it:

from urllib import request, parse
data = parse.urlencode('example.txt').encode()
req =  request.Request('http://example.com/api', data=data) 
resp = request.urlopen(req)

1 Answers1

0

I'd highly recommend using the requests package over urllib.

Making a POST request is as easy as:

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("https://httpbin.org/post", data=payload)
print(r.text)

Output:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "key1": "value1", 
    "key2": "value2"
  }, 
baduker
  • 19,152
  • 9
  • 33
  • 56
  • What would the payload dictionary be in my case? I know that wget's --post-file takes things as key-value pairs, but I just tried experimenting with the code you provided and I couldn't get it to work. – DataScienceNovice Mar 20 '21 at 17:59