Python Forum

Full Version: How to get valid error message while invoking REST API through Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Experts,

I am new to python. Have written code to invoke REST API performing poST operation. I am getting 400 Bad Request ERROR. When I try running the same data using SOAP UI tool I am getting 400 error but displaying valid error message.

How can get the valid error message through python scripting. Please find the below python script for oyur reference.

import requests
import json
import csv
import os
import pdb

user = 'abc'
password = 'abc'
autha = [user,password]

with open('D:\User\Projects\Python\PythonScripts\PjfRBS_LOAD1.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print("This is the first line of the file")
            line_count += 1
        else:
            RBSASSIGMENTID = str(row[1])
            #print("RBSASSIGMENTID" + RBSASSIGMENTID)
            PROJECTID = str(row[0])
            #print("PROJECTID" + PROJECTID)
            RESOURCECLASSNAME = row[3]
            #print("RESOURCECLASSNAME" + RESOURCECLASSNAME)
            FORMATNAME = row[4]
            #print("FORMATNAME" + FORMATNAME)
            RESOURCE_NAME = row[5]
            #print("RESOURCE_NAME" + RESOURCE_NAME)
            EMAILADDRESS = row[6]
            #print("EMAILADDRESS" + EMAILADDRESS)
            PROJECTNUMBER = row[2]
            #print("PROJECTNUMBER" + PROJECTNUMBER)
            PERSONID = str(row[7])
            #print("PERSONID" + PERSONID)
            RBS_URL = 'https://CLOUD/fscmRestApi/resources/11.13.18.05/projectPlanningRbs/'+RBSASSIGMENTID+'/child/Elements'
            print(RBS_URL)
            data = {"ResourceClassName": RESOURCECLASSNAME,"FormatName": FORMATNAME,"PersonId": PERSONID,"ResourceName":RESOURCE_NAME}
            jstr = json.dumps(data,indent=4)
            print(jstr)
            patch_response = requests.post(url = RBS_URL,auth=(user,password),json=jstr)
            if patch_response.status_code == 200:
                print('We are able to connect to PATCH REST API')
                print('Update for the Project = '+ PROJECTNUMBER + ', Project ID = '+ PROJECTID + ', RESOURCE_CLASSNAME ='+ RESOURCECLASSNAME + ', RESOURCE_NAME =' + RESOURCE_NAME + 'and EMAILADDRESS ='+ EMAILADDRESS)
                line_count += 1
            else:
                ##pdb.set_trace()
                patch_response.reason
                print('we are not able to connect to PATCH REST API '+ patch_response.reason + str(patch_response.status_code))
                ##print('Update for the Project = '+ PROJECTNUMBER + ', Project ID = '+ PROJECTID + ', RESOURCE_CLASSNAME ='+ RESOURCECLASSNAME + ', RESOURCE_NAME =' + RESOURCE_NAME + 'and EMAILADDRESS ='+ EMAILADDRESS)

    print('file Processed' + str(line_count) + 'lines.')