首页 > 解决方案 > 如何使用标头和数据在 Python 中正确执行 http 请求

问题描述

我正在尝试根据此处编写的文档获取一些东西:

这是我的代码:

import requests
import json

post_data = {"exchange": "NSE",
        "tradingsymbol": "INFY",
        "transaction_type": "BUY",
        "variety": "regular",
        "product": "CNC",
        "order_type": "MARKET",
        "quantity": 1,
        "price": 0,
        "trigger_price": 0
            }


header_data = {
     'X-Kite-Version': '3',
    'Authorization': 'token '+str(api_key)+":"+str(access_token),
    'Content-Type': 'application/json'
}

r = requests.post('https://api.kite.trade/margins/orders',
                   data= post_data,
                   headers=header_data)

print(r.text)

但我收到了这个回复

{"status":"error","message":"invalid json","data":{},"error_type":"InputException"}

我想知道,我做错了什么。

标签: python

解决方案


我没有尝试过,但看起来输入数据应该是一个列表/数组,而不是一个字典/对象。所以试试这个数据:

post_data = [
    {
        "exchange": "NSE",
        "tradingsymbol": "INFY",
        "transaction_type": "BUY",
        "variety": "regular",
        "product": "CNC",
        "order_type": "MARKET",
        "quantity": 1,
        "price": 0,
        "trigger_price": 0
    }
]

推荐阅读