0

I'm try to call a REST web-service I made on Salesforce from a Python script

@RestResource(urlMapping='/test_rest_api')

global with sharing class Test_RestAPI {

    @HttpPost
    global static void postFeed(String s){

       //my code
       //
    }
}

The first par of my script is identification and work well

the second part give me an error 400 Bad Request

def callapipost(self):
        ## Create URL
        urlpost = https://test.salesforce.com/services/apexrest/test_rest_api        
##Create Header
        headerpost = {'Authorization': 'Bearer '+self.bearer, 'Content-type': 'application/json'}
        print('url utilisee ' + urlpost)
        ## create full request
        req = urllib.request.Request(url=urlpost, data=bytes(urllib.parse.urlencode(
                {
                    "s": "Test"
                }),
                'UTF-8'),
            headers=headerpost)

        try:
            with urllib.request.urlopen(req):
                print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
                print('OK ! ')
                print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')

        except urllib.error.HTTPError as er:
            print(er.msg)
            raise er

    def run(self):
        self.authSF()
        self.callapipost()


SendToSFAPI = SendToSFAPI()

try:
    SendToSFAPI.run()
except urllib.error.HTTPError as err :
    print(err)

raise err

When I try acces this WS with WorkBench, I have no problem

des

Is there something I miss here?

  • Could be a firewall issue? – m Peixoto Mar 8 at 15:39
2

The payload should not be urlencoded. application/json expects literal JSON. The request should look like this over the wire:

POST /services/apexrest/test_rest_api HTTP/1.1
Host: mydomain.my.salesforce.com
Content-Length: 12
Authorization: Bearer MySessionIdWouldBeHere
Content-Type: application/json

{"s":"Test"}

My Python is a little rusty, so you'll have to adjust your code appropriately, but simply removing the url-encoding part should fix your problem.

0

I confirm @sfdcfox, JSON should not be urlencoded. Was following some exemple using urllib and I don't think this is the best function to do REST POST call to Salesforce (from this little experience, I may be wrong)

I used requests.request in my case to do it work :

myJson = { 's': 'Test' }
myHeader = {'Authorization': 'Bearer '+self.bearer, 'Content-type': 'application/json'}

response = requests.request('post', headers=myHeader, url=myInstanceSalesforce+'/services/apexrest/test_rest_api', json=myJson )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.