2016-12-02 19 views
0

我張貼到辦公室其餘365 API和正在創建轉儲按如下:Python/JSON - 命令很重要,爲什麼這個JSON發佈到REST API失敗?

def CreateEvent(auth, cal_id, subject, start_time, end_time, attendees, content): 
    create_url = 'https://outlook.office365.com/api/v1.0/me/calendars/{0}/events'.format(cal_id) 
    headers = {"Content-type": "application/json", "Accept": "application/json"} 
    data = {"Subject":"","Attendees": [],"End": {},"Start": {},"Body": {}} 
    data["Subject"] = subject 
    data["StartTimeZone"] = "GMT Standard Time" 
    data["Start"] = start_time 
    data["EndTimeZone"] = "GMT Standard Time" 
    data["End"] = end_time 
    data["Attendees"] = attendees 
    data["Body"]["ContentType"] = "Text" 
    data["Body"]["Content"] = content 
    content_data = json.dumps(data) 
    #return data 
    response = requests.post(create_url,data,headers=headers,auth=auth) 
    return response 

這將產生一個無序傾倒,我相信應該不會造成任何問題?

然而,後期使用ÿ當我手動我得到一個201,並且創建事件,發帖時使用產生以下轉儲功能,我得到一個400

y=""" 
{ 
    "Subject": "TESTTTT", 
    "Body": { 
    "ContentType": "HTML", 
    "Content": "I think it will meet our requirements!" 
    }, 
    "Start": "2016-12-02T11:30:00Z", 
    "StartTimeZone": "GMT Standard Time", 
    "End": "2016-12-02T11:45:00Z", 
    "EndTimeZone": "GMT Standard Time", 
    "Attendees": [ 
    { 
     "EmailAddress": { 
      "Name": "Alex ", 
      "Address": "[email protected]" 
     }, 
     "Type": "Required" 
    } 
    ] 
} 
""" 

什麼我的函數返回和給予400

{ 
    'Body': { 
     'Content': 'test data', 
     'ContentType': 'Text' 
    }, 
    'End': '2016-12-02T06:00:00Z', 
    'StartTimeZone': 'GMT Standard Time', 
    'EndTimeZone': 'GMT Standard Time', 
    'Start': '2016-12-02T02:00:00Z', 
    'Attendees': [{ 
     'EmailAddress': { 
      'Name': 'Alex ', 
      'Address': '[email protected]' 
     }, 
     'Type': 'Required' 
    }], 
    'Subject': 'Maintenance: test' 
} 
+0

您可能想首先在'fiddler'或類似工具中查看一些細節 – Shane

回答

1

一目瞭然,我相信你只需要改變

response = requests.post(create_url,data,headers=headers,auth=auth) 

response = requests.post(create_url,content_data,headers=headers,auth=auth) 

您在調用json.dumps()方法來序列化字典時是正確的。只需將該字符串傳遞給服務器即可。

+0

此外,OP原始輸出的問題是它使用單引號字符串,這在JSON中無效。 [JSON字符串_必須使用雙引號](http://json.org/)。 – Chris

+0

對。當Python將字典輸出爲字符串時,它使用單引號。如果OP要打印出json.dumps()結果,則會看到雙引號。 – gregbert

+0

我花了4個小時從這個atleast開始......感謝您的幫助! – AlexW