简体   繁体   English

Swagger API 和与 python 请求的交互

[英]Swagger API and interaction with python requests

A product was purchased to enable our users to send/receive SMS over HTTP.购买了一种产品,使我们的用户能够通过 HTTP 发送/接收 SMS。 Now it's my job to build it into our current CMS platform & database.现在我的工作是将它构建到我们当前的 CMS 平台和数据库中。 It's got a swagger API.它有一个 swagger API。

Here is the documentation for the specific POST request I am trying to send: POST: Send an SMS Message这是我尝试发送的特定 POST 请求的文档: POST: Send an SMS Message

Here is my simple python program to test the functionality.这是我用来测试功能的简单 python 程序。 I get a generic 500 internal server error response.我得到一个通用的 500 内部服务器错误响应。 What am I doing incorrectly?我做错了什么?

import requests

API_URL = "https://api.kenect.com/v1/conversations/messages"

headers = {
    'x-api-token': '****************',
    'x-api-key': '*******************',
    'Content-Type': 'application/json',
}

params = {
    'contactPhone': '158572968**',
    'locationId': '2045',
    'messageBody': 'test sms',
    'outgoing': 'true',           
}

r=requests.post(url = API_URL, headers = headers, params = params)

print(r)

There seems to be 2 issues:似乎有2个问题:

  1. Content type and payload encoding.内容类型和负载编码。

    You are using params parameter in the post method.您在post方法中使用params参数。 params is used with get method for passing data in the URL's query string . paramsget方法一起用于在 URL 的查询字符串中传递数据

    In the post method, depending on the required content type, you need to use either data parameter to send form-encoded data :post方法中,根据所需的内容类型,您需要使用任一data参数来发送表单编码数据

    r=requests.post(url = API_URL, headers = headers, data = params)

    or json parameter to send application/json payload:json参数来发送application/json负载:

    r=requests.post(url = API_URL, headers = headers, json = params)

    Remove the 'Content-Type' key from your headers dictionary.headers字典中删除 'Content-Type' 键。 data and json parameters will set up correct content type automatically. datajson参数将自动设置正确的内容类型。

  2. outgoing is not a valid request parameter for the /v1/conversations/messages resource. outgoing不是/v1/conversations/messages资源的有效请求参数。 This field is from the response object, not the request one.该字段来自响应对象,而不是请求对象。 Remove it from your payload.从您的有效负载中删除它。

So to sum up, for form-encoded payload the code should look like this:总而言之,对于表单编码的有效负载,代码应如下所示:

import requests

API_URL = "https://api.kenect.com/v1/conversations/messages"

headers = {
    'x-api-token': '****************',
    'x-api-key': '*******************',
}

params = {
    'contactPhone': '158572968**',
    'locationId': '2045',
    'messageBody': 'test sms',       
}

r=requests.post(url = API_URL, headers = headers, data = params)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM