Home > rest api > Rest API Parameters are not getting passed to method

Rest API Parameters are not getting passed to method

January 7Hits:3
Advertisement

I defined rest API method as follows -

@RestResource(urlMapping='/verifyaccount/v1/*')  global class VerifyAccountService {     @HttpPost     global static String VerifyAccount()     {            return 'VerifyAccountResult ==> ' + RestContext.request.params.get('AccountName');     } } 

and I am trying test it as follows - I know there is another way of testing this but I want to call it from another salesforce org and thats why I need to test it like this. and I did not specify any parameter to method itself because I wanted this method to be flexible and not bound to parameters defined in this method only.

Salesforce documentation says -

'If the Apex method has no parameters, Apex REST copies the HTTP request body into the RestRequest.requestBody property. If the method has parameters, then Apex REST attempts to deserialize the data into those parameters and the data won't be deserialized into the RestRequest.requestBody property.' Source

Http httpProtocol = new Http(); HttpRequest request = new HttpRequest(); request.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId()); request.setHeader('Content-Type', 'application/json'); request.setEndPoint('https://cs9.salesforce.com/services/apexrest/verifyaccount/v1/'); request.setMethod('POST'); String strbody = '{  "AccountName" : "Test Company", "Id" : "1234566" }'; request.setBody(strbody); HttpResponse response = httpProtocol.send(request); String jsonInput = response.getBody(); system.debug('===>'+jsonInput); 

Output is "VerifyAccountResult ==> null "

Answers

Your example has
RestContext.request.params.get('AccountName')

I think you need to use requestBody, which is a Blob.

@HttpPost
global static String VerifyAccount()
{
    RestRequest req = RestContext.request;
    Blob body = req.requestBody;
    String bodyString = body.toString();
    // TODO: Extract the parameter from the string
    return 'VerifyAccountResult ==> ' + bodyString );
}

You could format strBody in you example as JSON and then use JSON.deserialize or JSON.deserializeUntyped to get the values out in Apex.

Your input JSON

{
"AccountName": "Test Company",
"Id": "1234566"
}

Corresponding APEX Class for the above JSON data

public class Jsondata {  //Have as a separate or as an Inner Class

public String AccountName;
public String Id;

 }

The Modified code for your implementation

@HttpPost
global static String VerifyAccount(){
RestRequest req = RestContext.request;
Blob body = req.requestBody;
String bodyString = body.toString();

//Deserializing the data sent into concrete SFDC objects
    Jsondata jsonwrap =(Jsondata)JSON.deserialize(bodyString,Jsondata.class);

return 'VerifyAccountResult ==> ' + jsonwrap.AccountName);
}

Tags:rest api

Related Articles

  • Rest API Parameters are not getting passed to methodJanuary 7

    I defined rest API method as follows - @RestResource(urlMapping='/verifyaccount/v1/*') global class VerifyAccountService { @HttpPost global static String VerifyAccount() { return 'VerifyAccountResult ==> ' + RestContext.request.params.get('AccountNam

  • What parameters are ok to pass to 7-zip .exe file creation while using the GUI

    What parameters are ok to pass to 7-zip .exe file creation while using the GUIFebruary 23

    What parameters are ok to pass to the create archive wizard , in the 7-zip GUI, when you are creating a self extracting archive? The 7-Zip GUI has a field that allows you to type in multiple parameters. I tried an obvious parameter (shown below) but

  • Passing a method's code as an argument in a typesafe wayMarch 15

    Passing a method as an argument is not a problem: type TSomething = class Msg: string; procedure Show; end; procedure TSomething.Show; begin ShowMessage(Msg); end; type TProc = procedure of object; procedure Test(Proc: TProc); begin Proc; end; proced

  • Android: Error in flow of passing through methodsJanuary 25

    I am trying to pass a text output into a regex method whereby I can take this entire text output and extract out the email address. For example, I have the text output below: Taria Joseph General Manager 96523325 [email protected] I want to pas

  • Invalid parameter information was passed to method 'differential.parsecommitmessage'February 1

    It show me an error: ERR-CONDUIT-CORE: Invalid parameter information was passed to method `differential.parsecommitmessage`. (Run with `--trace` for a full exception trace.) When I type arc diff in CMD. I use arcanist and php to review my code, and t

  • Java - how do I pass a method as parameter?February 6

    I have a stanza of code that is repeatedly used. Here are two examples: public java.sql.Struct createStruct(String typeName, Object[] attributes) { String searchPath = getSearchPath(); String name = setSearchPathToSchema(typeName); Struct ret = deleg

  • Why does passing a method as an argument (&block) not work?February 7

    clock takes a block: def clock(&block) hours = Time.new.hour puts hours hours.times do block.call end end This works, and puts "DONG" on the screen, based on the hours of today: clock do puts "DONG..." end I'm trying to pass dong m

  • How do you pass parameters to an Express post HTTP method?February 17

    I'm building a simple REST API (with PouchDB and Vue.js). Right now, I can create projects with a few fields: server.js: var express = require('express') var PouchDB = require('pouchdb') var app = express() var db = new PouchDB('vuedb') app.post('/pr

  • NEW API parameters for ISPConfig 3.0.5.1.July 7

    Hi Guys, where are all the parameters description for each API method? I need to update our ShineISP software. Is there a webpage with an updated documentation? thanks --------------Solutions------------- You can get the parameters from the dbispconf

  • Get parameterized type of Lists when retrieving methods and return types from Tooling APIJanuary 7

    When issuing a query against the ApexClass with the Tooling API, I can get back return types and method parameters. However, they simply return "LIST" for lists. Is there a way to get back the parameterized type of those lists? E.g. instead of &

  • Visualforce - Apex Parameters are not getting passed to controllerApril 21

    VF Code <apex:pageBlock title="New Expense" rendered="{!isNewExpense}" id="pb"> <apex:pageBlockButtons > <apex:commandButton value="Save New Expense" action="{!save}" rerender="pb"

  • Nginx & PHP-FPM: Query parameters won't be passed to PHPApril 25

    I am currently setting up a machine for local development using Vagrant. Everything runs as it should, expect query parameters aren't passed to PHP on subpages. That means on www.example.com/?a=b, the query parameter is accessible, but on www.example

  • Rails validating API parametersOctober 25

    I wanted to keep my API request logic separate form the controller logic. I therefore make use of a separate model (EmailChecker) that creates an instance of this class via EmailChecker.new(params). Then I can check the new instance with valid?. When

  • rest api testing using chakram, parameter passing in url using variableJanuary 15

    I am using chakram for restapi testing. https://github.com/dareid/chakram I have two api's chained together. 1st is post request which gives the user id. post('/login', {"user" : "user1", "password": "password"}) 2n

  • Pass Dynamic List of Parameters and Values to a C# Method to execute SQL Stored ProcedureJanuary 25

    I have a method in C# to execute a stored procedure. This will be called from a Script Component in SSIS 2014 (which also calls out to a web service for data). I'd like to be able to pass a dynamic list of SQL Parameters and Values. I was thinking ab

  • Java - Parameters are not being passed into function when expected to beJanuary 27

    I am attempting to run a method rgbScore() which passes in parameters from previous methods to calculate the difference between two pixels of a image. I would expect the result to be the difference between the two pixels but all I get is (0,0,0) ...

  • how to pass message and data using web Api i am able to pass message or data one at a timeFebruary 17

    if (u != null && user.Password == Password) { var message = string.Format("Sucessfull login"); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK,message); return response; } I am very new to web api i want to pass m

  • Passing parameters through action-state for bean methodJanuary 19

    I have a simple question. I have myView.xhtml, my-flow.xml and myBean.java. In myView.xhtml I have <h:outputText value="otherBean.value"/> <h:commandLink action="myAction"/> In my-flow.xml I have (let's suppose transition f

  • Handle query string parameters when multiple values passingFebruary 9

    Below is my script $("#locSearchSubmitBtn").click(function(){ var locname = $("#location").val(); var qparam = window.location.search.replace(/[\\?&]q=([^&#]*)/g,'') history.pushState({},"qparam", '?q='+locname+qparam

  • Rest API Parameters are received as nullMay 8

    Apex class - @RestResource(urlMapping='/account') global class createAccount { @HttpPost global static void createAcc() { //-- Data coming from request String strFirstName = RestContext.request.params.get('First_Name'); String strLastName = RestConte

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.622 s.