[英]How to send a POST request to a REST API on a localhost with Python?
[英]How to send POST request in Python (Python REST API)?
我想向 VNF 发送 POST 请求以保存服务。
这是我的代码。
class APIClient:
def __init__(self, api_type, auth=None):
if api_type == 'EXTERNAL':
self.auth_client = auth
def api_call(self, http_verb, base_url, api_endpoint, headers=None, request_body=None, params=None):
if headers is not None:
headers = merge_dicts(headers, auth_header)
else:
headers = auth_header
url_endpoint = base_url + api_endpoint
request_body = json.dumps(request_body)
if http_verb == 'POST':
api_resp = requests.post(url_endpoint, data=request_body, headers=headers)
return api_resp
else:
return False
def add_service():
for service in service_list:
dict = service.view_service()
auth_dict = {
'server_url': 'https://authserver.nisha.com/auth/',
'client_id': 'vnf_api',
'realm_name': 'nisha,
'client_secret_key': 'abcd12345',
'grant_type': 'client_credentials'
}
api_client = APIClient(api_type='EXTERNAL', auth=auth_dict)
response = api_client.api_call(http_verb='POST',
base_url='http://0.0.0.0:5054',
api_endpoint='/vnf/service-management/v1/services',
request_body=f'{dict}')
print(response)
if response.ok:
print("success")
else:
print("no")
当我运行此代码时,它会打印
<Response [415]>
no
VNF 端的所有功能都可以正常工作,我对 GET 服务 api 调用没有任何问题。 如何解决这个问题?
如果您需要将application/json
数据发布到端点,则需要使用requests.post
中的json
kwarg 而不是data
kwarg。
在requests.post
中显示json
和data
kwargs 之间的区别:
import requests
from requests import Request
# This is form-encoded
r = Request('POST', 'https://myurl.com', headers={'hello': 'world'}, data={'some': 'data'})
x = r.prepare()
x.headers
# note the content-type here
{'hello': 'world', 'Content-Length': '9', 'Content-Type': 'application/x-www-form-urlencoded'}
# This is json content
r = Request('POST', 'https://myurl.com', headers={'hello': 'world'}, json={'some': 'data'})
x = r.prepare()
x.headers
{'hello': 'world', 'Content-Length': '16', 'Content-Type': 'application/json'}
所以你根本不需要json.dumps
步骤:
url_endpoint = base_url + api_endpoint
if http_verb == 'POST':
api_resp = requests.post(url_endpoint, json=request_body, headers=headers)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.