how to POST contents of JSON file to RESTFUL API with Python using requests module

前端 未结 4 1656
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 15:30

Okay, I give up. I am trying to post the contents of a file that contains JSON. The contents of the file look like this:


{
     \"id”:99999999,
              


        
相关标签:
4条回答
  • 2020-12-25 15:48

    First of all your json file does not contain valid json. as in,"id”-here the closing quotation mark is different than the opening quotation mark. And other ID fields have the same error. Make it like this "id".

    now you can do it like this,

    import requests
    import json
    with open('example.json') as json_file:
        json_data = json.load(json_file)
    
    headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}
    
    r = requests.post('https://api.example.com/api/dir/v1/accounts/9999999/orders', data=json.dumps(json_data), headers=headers)
    
    0 讨论(0)
  • 2020-12-25 15:49

    I have done below code while learning Open API and works fine for me.

    `
    import requests
    url="your url"
    json_data = {"id":"k123","name":"abc"}
    resp = requests.post(url=url,json=json_data)
    print(resp.status_code)
    print(resp.text)
    `
    
    0 讨论(0)
  • 2020-12-25 16:06

    This should work, but it's meant for very large files.

    import requests
    
    url = 'https://api.example.com/api/dir/v1/accounts/9999999/orders'
    headers = {'Authorization' : ‘(some auth code)’, 'Accept' : 'application/json', 'Content-Type' : 'application/json'}
    r = requests.post(url, data=open('example.json', 'rb'), headers=headers)
    

    If you want to send a smaller file, send it as a string.

    contents = open('example.json', 'rb').read()
    r = requests.post(url, data=contents, headers=headers)
    
    0 讨论(0)
  • 2020-12-25 16:10

    You need to parse the JSON, and pass that the body like so:

    import requests
    import json
    json_data = None
    
    with open('example.json') as json_file:
        json_data = json.load(json_file)
    
    auth=('token', 'example')
    
    r = requests.post('https://api.example.com/api/dir/v1/accounts/9999999/orders', json=json_data, auth=auth)
    
    0 讨论(0)
提交回复
热议问题