We use the RestRequest class to access incoming request in apex rest webservice.
Below are the method available with RestRequest class.
1) headers
Returns the headers that are received by the request.
The return type is of Type: Map<String, String>.
2) httpMethod
Returns one of the supported HTTP request methods.
The return type is of Type: String.
Possible values returned are:
- DELETE
- GET
- HEAD
- PATCH
- POST
- PUT
3) params
Returns the parameters that are received by the request.
The return type is of Type: Map<String, String>.
4) remoteAddress
Returns the IP address of the client making the request.
The return type is of Type: Map<String, String>.
5) requestBody
Returns or sets the body of the request.
The return type is of Type: Blob.
6) requestURI
Returns or sets everything after the host in the HTTP request string.
The return type is of Type: String.
7) resourcePath
Returns the REST resource path for the request.
The return type is of Type: String.
Now, let us try to understand with an example.
Let us try to call the below webservice from workbench.
Below is an example of webservice which need id or any unique identifier as a parameter in request and it will return record associated with it.
I have put system.debug statements in webservice to debug the "headers" and "httpMethod".
@RestResource(urlMapping='/getAccountOnExternalIdtofetchsinglerecord/*')
global with sharing class getAccounttoSingleRecord {
@Httpget
global static Account fettringchAccount(){
Account obj=new Account();
RestRequest req = RestContext.request;
RestResponse res = Restcontext.response;
System.debug('Request Headers-->'+req.headers);
System.debug('Request Method-->'+req.httpMethod);
System.debug('Request Body-->'+req.requestBody);
string accId =
req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
obj=[Select id , name from Account where id=:accId];
//string ser=JSON.Serialize(obj);
return obj;
}
}
No comments:
Post a Comment