0

Following is my code snippet. How can I modify my getUrlAndHeader(), so that my requests.post works. Right now I get 404 response if I use getUrlAndHeader() . Can someone please help?

import requests
def getUrlAndHeader():
    return "https://someurl.com, headers={'key1': 'val1', 'key2': 'val2'}"

if __name__ == "__main__":
    #200#response = requests.post("https://someurl.com", headers={'key1': 'val1', 'key2': 'val2'}, json=[])
    #404#response = requests.post(getUrlAndHeader(), json=[])
    #print response
sai
  • 97
  • 2
  • 11

2 Answers2

5

You are trying to return a single string. You could return a tuple, like

def getUrlAndHeader():
    return "https://someurl.com", {'headers': {'key1': 'val1', 'key2': 'val2'}}

but you won't be able to pass the return value directly to the argument list of post. (There's nothing you can unpack as a mix of positional and keyword arguments.) Instead, do something like

if __name__ == "__main__":
    url, other = getUrlAndHeader()
    response = requests.post(url, json=[], **other)
chepner
  • 497,756
  • 71
  • 530
  • 681
0

If you are looking how to make post API call then please refer this Python send POST with header

For your problem you can also solve this way.

import requests
import json


def get_url_and_headers():
    return {"url": "https://someurl.com", "headers": "{'key1': 'val1', 'key2': 'val2'}"}


if __name__ == "__main__":
    res = get_url_and_headers()
    my_payload = {"a": 1, "b": 2}
    response = requests.post(res['url'], data=json.dumps(my_payload), headers=res['headers'])
    print(response.content)
Shakeel
  • 1,869
  • 15
  • 23