Nisha
Nisha

Reputation: 389

How to send POST request in Python (Python REST API)?

I want to send POST request to VNF to save Services .

Here is my code .

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")

When I run this code it prints

<Response [415]>
no

All the functions in VNF side are working without issues and I have no issue with GET services api call. How to fix this ?

Upvotes: 1

Views: 5258

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

If you need to post application/json data to an endpoint, you need to use the json kwarg in requests.post rather than the data kwarg.

To show the difference between the json and data kwargs in requests.post:

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'}

So you don't need the json.dumps step here at all:

        url_endpoint = base_url + api_endpoint

        if http_verb == 'POST':
            api_resp = requests.post(url_endpoint, json=request_body, headers=headers)

Upvotes: 2

Related Questions