function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sean RockSean Rock 

How to generate a Session ID

Hi

New to SalesForce. I'm trying to generate a Lead using the rest api and thankfully I've had a good reply. However the next hurdle is solving this error that is returned from the api call.
[
    {
        "message": "Session expired or invalid",
        "errorCode": "INVALID_SESSION_ID"
    }
]

I've reviewed the documentation on authorisation and its just a tad confusing. It states do not use SessionID if you are handling someones password, then states you must include username/password when getting a session id. Or am I missing something?

It also mentions client id and client secret. Can anyone tell me where I can find those? I've seen a few posts where its mentioned you can go to Create > Apps or Build > Create > Apps however I do not see those actions. 

Can anyone point me in the right direction? I'm using a developer account.

Thanks.



 
SwethaSwetha (Salesforce Developers) 
HI Sean,
Does this give the same message when you reauthenticate yourself?
Recomend reviewing this article: https://help.salesforce.com/articleView?id=000335524&type=1&mode=1

If it helps, please mark this answer as best.Thank you
Sean RockSean Rock
Hi and thanks for your reponse.

How do I reauthenticate myself?
 
SwethaSwetha (Salesforce Developers) 
HI Sean,
I see your ask is a continuation of https://developer.salesforce.com/forums/ForumsMain?id=9062I000000IUg1

To overcome the "Session expired" message, you need to replace below the bold line with your current session
Authorization: Bearer 00D0o0000015jPn!ARgAQPiIGhuYGUG_c0HDKNR0hxTX9zS82Fv1lIuqn4rapFJHPR422gLyi10rF8Auukb._hj9pj532DP7IajQV36lyKpUNEXdxvL
Let me know which tool you are using so I can suggest accordingly

You can create a VF page as below and fetch the session ID to use this for REST API testing
<apex:page >
     {!$Api.Session_ID}
</apex:page>

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you
 
Sean RockSean Rock
Thank you again for your help.

I've used that Bearer token however it yields the same result. 

Here is my original thread: https://developer.salesforce.com/forums/ForumsMain?id=9062I000000IUg1QAG

I'm using Postman.

I'm not familar with VF pages.

Thanks again.

 
Maharajan CMaharajan C
Hi,

You can follow the below blogs to get the session Id in postman.

https://www.sfdcstop.com/2019/01/how-to-connect-to-salesforce-with.html
https://blog.mkorman.uk/using-postman-to-explore-salesforce-restful-web-services/
https://jdspaceit.wordpress.com/2016/09/26/using-postman-for-testing-salesforce-rest-apis/


And one more we have the chrome extension called EditThisCookie. With help of this extension you can directly get the Session Id from your browser if you have already logged in the Salesforce in browser. So that you can easily test the service.
https://chrome.google.com/webstore/detail/editthiscookie/fngmhnnpilhplaeedifhccceomclgfbg

User-added image



In Apex we will use the below way to get the Session Id.
String reqBody ='grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password+securityToken;
        system.debug('Auth reqBody ==> ' + reqBody);
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqBody);
        req.setMethod('POST');
        req.setEndpoint(accesstoken_url);    
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
        HttpResponse res=h.send(req);
        system.debug(' Authorization Response ==> '+ res.getBody());
        deserializeResponse resp = (deserializeResponse)JSON.deserialize(res.getBody(),deserializeResponse.class);
        system.debug('resp==> '+ resp.access_token);


Thanks,
Maharajan.C

 
Sean RockSean Rock
Thanks for your reply.

The first link was helpful but did not solve my issue. I have used the chrome extension to get the session id from the cookie and as instructed in the documentation, substituted the session id for the token. However that still returned an error.
 
[
    {
        "message": "Session expired or invalid",
        "errorCode": "INVALID_SESSION_ID"
    }
]

Any idea what I might try next?

Thanks.
 
Sean RockSean Rock
Anyone?
SwethaSwetha (Salesforce Developers) 
HI Sean,
Can you share the exact steps of postman you are using? 
Sean RockSean Rock
Hi

I used your example Authorization parameter as above
Authorization: Bearer 00D0o0000015jPn!ARgAQPiIGhuYGUG_c0HDKNR0hxTX9zS82Fv1lIuqn4rapFJHPR422gLyi10rF8Auukb._hj9pj532DP7IajQV36lyKpUNEXdxvL
That returned this response.
[
    {
        "message": "Session expired or invalid",
        "errorCode": "INVALID_SESSION_ID"
    }
]
I tried to get a sessionid using this endpoint
https://login.salesforce.com/services/oauth2/token
And passing a username, password, grand_type, client_id and client_secret in the body of the request. I reset my Security Token and added that onto my password. I double checked to ensure all the parameter values were correct.

That resulted in this response
{
    "error": "unsupported_grant_type",
    "error_description": "grant type not supported"
}

I followed one suggestion of using the cookie from my browser, once logged in to salesforce. I replaced the Bearer token value with that cookie value and tried the original request (create a lead) again however I still get the session expired or invalid response.


Thank you.



 
SwethaSwetha (Salesforce Developers) 
HI Sean,
I have followed the steps in article: https://jdspaceit.wordpress.com/2016/09/26/using-postman-for-testing-salesforce-rest-apis/ and could fetch a new session

>Create a new connected app in salesforce(Setup> Apps> New Connected App>Use Callback URL    
https://www.getpostman.com/oauth2/callback )

Steps in postman: 
1. Create a new "request".
2. Choose "GET" request and enter your URL which in my case is 
https://cti712-dev-ed.my.salesforce.com/services/data/v48.0/sobjects/Lead/00Q6F00001DIItPUAX

3. select Authorization> type> Oauth2.0 from the dropdown > Click Get New Access Token Button

4.Enter Auth URL : https://login.salesforce.com/services/oauth2/authorize
5. Enter access token URL https://login.salesforce.com/services/oauth2/token
6. Enter consumer Key, secret key from connected app
7. Choose grant type: Authorization code and click Request Token
User-added image
8. Click the token name and copy the access code.
9. In the header, enter Key "Authorization" and its value as "Bearer *your copied access token* and send the request
User-added imageUser-added image
Happy to answer any follow up queries.

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you
 
SwethaSwetha (Salesforce Developers) 
A helpful video: https://www.youtube.com/watch?v=WdAhD6p1nKM&ab_channel=SalesforceApexHours
Sean RockSean Rock
Thank you, however I still recieve the error.

error
 
SwethaSwetha (Salesforce Developers) 
HI Sean,
I suspect there is a space in the grant_type you are passing.
Can you exactly use grant_type (text) with value "password". I did the same operation and could succeed.When I gave a wrong value it threw the same error you faced.
User-added image

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you
Sean RockSean Rock
Thank you. Eventually after many attempts, deleting and recreating the connected app, more failed attempts, then restaring Postman I got an access token. However when I use that access token to create a lead I get an objectDescribe response and no Lead is created.
{
    "objectDescribe": {
        "activateable": false,
        "createable": true,
        "custom": false,
        "customSetting": false,
        "deepCloneable": false,
        "deletable": true,
        "deprecatedAndHidden": false,
        "feedEnabled": true,
        "hasSubtypes": false,
        "isInterface": false,
        "isSubtype": false,
        "keyPrefix": "00Q",
        "label": "Lead",
        "labelPlural": "Leads",
        "layoutable": true,
        "mergeable": true,
        "mruEnabled": true,
        "name": "Lead",
        "queryable": true,
        "replicateable": true,
        "retrieveable": true,
        "searchable": true,
        "triggerable": true,
        "undeletable": true,
        "updateable": true,
        "urls": {
            "compactLayouts": "/services/data/v48.0/sobjects/Lead/describe/compactLayouts",
            "rowTemplate": "/services/data/v48.0/sobjects/Lead/{ID}",
            "approvalLayouts": "/services/data/v48.0/sobjects/Lead/describe/approvalLayouts",
            "defaultValues": "/services/data/v48.0/sobjects/Lead/defaultValues?recordTypeId&fields",
            "listviews": "/services/data/v48.0/sobjects/Lead/listviews",
            "describe": "/services/data/v48.0/sobjects/Lead/describe",
            "quickActions": "/services/data/v48.0/sobjects/Lead/quickActions",
            "layouts": "/services/data/v48.0/sobjects/Lead/describe/layouts",
            "sobject": "/services/data/v48.0/sobjects/Lead"
        }
    },
    "recentItems": []
}

 
Sean RockSean Rock
Anyone?
SwethaSwetha (Salesforce Developers) 
I tried with below and could succeed.Can you try below parameters and see if it works

POST URL:
https://yourInstanceURL.my.salesforce.com/services/data/v48.0/sobjects/lead/

Request Body:

{
  "LastName" : "Express Logistics and Transport11",
  "Company" : "Forums"
}

Headers:
Authorization "Bearer 0DKF000002Rhob!ARwAQGLRt6l5OdDmVjJhuqSZqIq.uS5q73QnwPEIk746g3Ps92Bg9034jTXvJpyz0Qfmh"
Content-Type "application/json"
User-added image
Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you
Sean RockSean Rock
Hi and thansk for your reply. I get the invalid session error again.
[
    {
        "message": "Session expired or invalid",
        "errorCode": "INVALID_SESSION_ID"
    }
]

 
Sean RockSean Rock
Any one else have any suggestion as to what I can try? Nothing appears to work.
Dan Bacon 9Dan Bacon 9
It's really useful and helpful with Swetha's reply. Please refer to her steps.
Ashish BurnwalAshish Burnwal
If you want see client key and client secret Setup->App Manager->dropdown on the api integration ->View