I want to generate a simple post call from Apex for the access token. I am new to Apex and Rest so is there someone explain me how to do that?
I have endpointurl, client _secret, client_id, scope, and grant_type is Client_credentials'.
I tried to run this in Postman and it works fine but not in salesforce.
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://xxx.xxx.eu/o/oauth2/token');
string mybody='{"client_id":"xxxx","client_secret":"xxxx","grant_type":"client_credentials","scope": "xxx.Rest.everything"}';
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json;charset=UTF-8');
// Set the body as a JSON object
request.setBody(mybody);
HttpResponse response = http.send(request);
// Parse the JSON response
if (response.getStatusCode() != 201) {
System.debug('The status code returned was not expected: ' +
response.getStatusCode() + ' ' + response.getStatus());
} else {
System.debug(response.getBody());
}
´´´´
Have you added the remote site? It is the probable reason I believe.
If not, try
From Setup, enter Remote Site Settings in the Quick Find box, then
select Remote Site Settings.
Click New Remote Site.
Enter a descriptive term for the Remote Site Name.
Enter the URL for
the remote site. Optionally, enter a description of the site.
Click Save
Related
I am working on a gamification project whose goal is to build a WebGL game with Unity and post the final score as a grade on an assignment using the canvas LMS API. I need to know two things: how to authenticate using a bearer token for now (I know how to create the token already and I will need to use auth 2.0 later) and how to post a grade on an assignment using UnityWeb Request or similar. I have tried using restsharp, the vs code recognized it, but Unity did not. Also tried making a connection with node.js, Unity and node.js connected successfully, but the node wrappers I was using did not work.
In the worst cenario I would like to be able to post a comment on the assignment (I would pass the final grade as a string).
This is what I've tried with httpWebRequest:
string api_token = "bearer token here";
//initializing HttpWebRequest object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("domain here");
IWebProxy theProxy = request.Proxy;
if (theProxy != null)
{
theProxy.Credentials = CredentialCache.DefaultCredentials;
}
CookieContainer cookies = new CookieContainer();
request.UseDefaultCredentials = true;
request.CookieContainer = cookies;
request.ContentType = "application/json";
request.CookieContainer = cookies;
// write the "Authorization" header
request.Headers.Add("Authorization", "Basic " + api_token);
request.Method = "POST";
// get the response
//WebResponse response = request.GetResponse();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
Debug.Log(reader.ReadToEnd());
}
I need the node wrappers to do authentication and the post request.
The node wrappers: c10. I've tried with this one a lot and
node-canvas-api
I can access the api and post using postman.
I found out I can use code snippets on postman to retrieve the request in a certain language. With this, I didn't need the python APIs anymore as I was able to get the code directly. I still don't know why Unity did not recognize restSharp, but python solved my problem.
As it was hard for me to find how to post grades and comments on Canvas lms I will leave the PATH here for anyone who has the same problem:
PUT /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id
the query params are:
comment[text_comment] and submission[posted_grade].
When users signup for our application, we ask them to go through the oAuth process. We ask them for their organisation first, so we can use the access token we receive during oauth to make requests.
Here is a sample of the code we use to do that:
var client = new RestClient();
var createItemRequest = new RestRequest("https://app.vssps.visualstudio.com/oauth2/token", Method.POST);
string body = $"client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&" +
$"client_assertion={HttpUtility.UrlEncode(clientSecret)}&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" +
$"&assertion={HttpUtility.UrlEncode(code)}&redirect_uri={redirectUrl}";
var formData = Encoding.UTF8.GetBytes(body);
createItemRequest.AddParameter("application/x-www-form-urlencoded", formData, ParameterType.RequestBody);
var accessTokenResponse = client.Execute(createItemRequest).Content;
_logger.LogInformation($"accessToken response: {accessTokenResponse}");
var accessTokenObject = JsonConvert.DeserializeObject<AccessTokenResponse>(accessTokenResponse);
if (accessTokenObject != null
&& !string.IsNullOrEmpty(accessTokenObject.AccessToken)
&& !string.IsNullOrEmpty(accessTokenObject.RefreshToken))
{
_logger.LogInformation($"We have access token and refresh");
}
We always manage to get the refresh + access tokens for every user. Directly after this call we make a "get all projects call" to test the connection and tokens. For some users signing up when we make this call to check we can see them, some users receive a 203 response when we use the access token to make the first call (to get a list of projects). The request looks like:
The HTML returns:
My question is, why do some users receive a 203 and some not? We have NO idea of what to tell the user when this happens - what do they check? Why does this happen? And how can they fix it?
I am trying to fetch records from a scratch org using the tooling API provided by salesforce and user access token. Lets say
accesstoken = "abcd"
url = "https://example.my.salesforce.com/services/data/v49.0/tooling/query?q=SELECT+Id,Name+FROM+Account"
I have used axios node module to make the API call as given below
const options = {
headers: {
"Authorization": "Bearer " + accessToken,
"Content-Type": "application/json"
}
};
axios.get(url, options).then(response => {
console.log(response.status);
if(response.status == 200){
console.log(response.data);
} else {
//do something else
}
});
The call responds with a status 200 i.e the request provided a response. But instead of correct records from Account object, I get the login html page
' Login | Salesforcehtml{visibility:
hidden;}a{color:#0070d2;}body{background-color:#F4F6F9;}#content,.container{background-color:#ffffff;}#header{color:#16325c;}body{display:
table;
width:100%;}#content{margin-bottom:24px;}#wrap{height:100%;} html { visibility: hidden; } if (self == top)
{document.documentElement.style.visibility = 'visible';} else
{document.write = ''; top.location = self.location;
setTimeout(function(){document.body.innerHTML='';},
1);window.self.onload=function(evt){document.body.innerHTML='';};}var
SFDCSessionVars={"server":"https://test.salesforce.com/login/sessionserver212.html","im":true,"ah":"active","save":"Save","saveOne":"Save
1 Change","sum":"#p# Saved Usernames","iaac":false,"hac":"Choose a
Username","suo":"1 Saved Username","title":" |
Salesforce","saveMany":"Save #p#
Changes","lpt":"Login","lllbl":"Lightning
Login","host":"test.salesforce.com","le":false,"heu":"Edit Username
List","ic":false,"lh":false,"ur":"https://business-data-8148-dev-ed.cs79.my.salesforce.com","hidp":"Log
In Using","ih":"inactive","dc":"Username removed. Click Save to Commit
Changes."};LoginHint.hideLoginForm();Edit ListSaveCancel
UsernamePassword Caps Lock is on.Remember
meForgot Your
Password?To go to your company's login
page, enter the custom domain name.Custom Domainhttps://domain.my.salesforce.comContinueBackLog In with a Different
Username© 2020
salesforce.com, inc. All rights reserved.<iframe frameborder="0" src="/s.gif" id="marketing"
name="marketing" scrolling="no" title="Marketing"
tabindex="-1"sandbox="allow-forms allow-pointer-lock allow-popups
allow-same-origin allow-scripts" >LoginLoginHint.getSavedIdentities(false);function
handleLogin(){document.login.un.value=document.login.username.value;document.login.width.value=screen.width;document.login.height.value=screen.height;document.getElementById("Login").disabled=true;document.getElementById("login_form").submit();}function
lazyload(){document.getElementById("pwcapsicon").src="/img/icon/capslock_blue.png";document.getElementById("marketing").src="https://c.salesforce.com/login-messages/promos.html";}loader();
'
Does anyone know what am I missing in here? According to salesforce documentation
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm
the accessToken in the header should be enough to make the API call.
Note: I gained the access token by running
sfdx force:user:display -u <username>
Your query is wrong. You selected Tooling API service which is for metadata (info about classes, triggers, objects, fields, deployments, running unit tests...). If you want to query Accounts - that's normal data. Try just /services/data/v49.0/query?q=SELECT+Id,Name+FROM+Account
I don't think you need Content-Type header in there. You don't POST anything. At best you can send Accept (application/json, application/xml)
Are you sure the session id was valid? As in you could go to the org, Setup -> Session management, see it there? Or in the user's login history?
It might be that your SF admin did something nasty like locking sessions down to IP from which they originated or maybe the user doesn't have API access... See if you can create your call in Workbench -> Utilities -> REST Explorer first, then go back to Axios?
I want to integrate SalesForce with Facebook Messenger. For this I've retrieved access token, app id , app secret. When I hit a HTTP request in developer console to send a message then there is an error.
In the given code it is not accepting messages as parameter throwing error but working without messages.
ref: https://developers.facebook.com/docs/messenger-platform/send-messages/?translation#sending_text
Httprequest req = new httpRequest();
req.setEndPoint('https://graph.facebook.com/v5.0/1798927698340/messages?access_token={PUT-ACCESS-TOKEN-HERE}');
String body = '{'+
'"recipient": {'+
'"id": "100042977199143"'+
'},'+
'"message": {'+
'"text": "hello, world!"' +
'}' +
'}';
req.setMethod('POST');
req.setHeader('Content-Type','application/json');
Http h = new Http();
HttpResponse res = h.send(req);
system.debug(res.getBody());
error message :
16:55:58:127 USER_DEBUG [16]|DEBUG|{"error":{"message":"Unsupported
post request. Object with ID 'me' does not exist, cannot be loaded due
to missing permissions, or does not support this operation. Please
read the Graph API documentation at
https://developers.facebook.com/docs/graph-api","type":"GraphMethodException","code":100,"error_subcode":33,"fbtrace_id":"AcqDT5M6mGXSOCr4mOd3kDf"}}
actual response : success = true
This problem arises sometimes when we use invalid access token or user access token instead of page access token.
Hi i am using client server, i want to fetch the response from an api which is invoking after clicking a button through selenium code , i create one method to invoke that API, but i got an error connection refused.below is my method :
Response response = RestAssured.get("https://diveui-dive-nonprod.telitcaas1.t-internal.com/case-requirement-service/1.0/caseGroupRequirement/BPFRMHAKEL/0");
CaseRequirement caseRequirement = (CaseRequirement) response.getBody();
System.out.println("Response Body is => " + caseRequirement.getRequirementId());
return String.valueOf(caseRequirement.getRequirementId());
}
can someone help me on this?