SalesForce.com – Accessing using Web Services and Scripting – Part 3

 

Powershell – SalesForce.com – REST Example :

CLS

function Get-AuthorizationTokenWithUsernamePasswordFlow ` 
($client_id, $client_secret, $username, $password, $security_token)
{
    Add-Type -AssemblyName System.Web

    # $uri = "https://test.salesforce.com/services/oauth2/token";
    $uri = "https://login.salesforce.com/services/oauth2/token";
    $grant_type = "password";

    $username = [System.Web.HttpUtility]::UrlEncode($username)
    $password = [System.Web.HttpUtility]::UrlEncode($password)

    $requestBody = "";
    $requestBody += "grant_type=$grant_type";
    $requestBody += "&client_id=$client_id";
    $requestBody += "&client_secret=$client_secret";
    $requestBody += "&username=$username";
    $requestBody += "&password=$password$security_token";

    
    Write-Host "Uri:" $uri
    Write-Host "Body:" $requestBody

    Invoke-RestMethod -Method Post -Uri $uri -Body $requestBody
}

# usage create a ClientID and ClientSecret
# https://help.salesforce.com/apex/HTViewSolution?id=000205876&language=en_US

# https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com
# Obtaining a Token in an Autonomous Client (Username and Password Flow)

$Cred = Get-Credential -credential "Email.Address@Company.com"
$username = $Cred.UserName
$password = $Cred.GetNetworkCredential().Password $client_id = "YOUR CLIENT ID";
$client_secret = "YOUR CLIENT SECRET";
$security_token = "YOUR SECURITY TOKEN";

# Debug
 Get-AuthorizationTokenWithUsernamePasswordFlow ` 
 $client_id $client_secret $username $password $security_token

$Token = Get-AuthorizationTokenWithUsernamePasswordFlow ` 
$client_id $client_secret $username $password $security_token

$URI = $Token.instance_url+"/services/data/v20.0/"

$Response = Invoke-RestMethod -URI $URI -Method GET ` 
-Headers @{"Authorization" = "OAuth " + $Token.access_token};

Write-Host ""

# Response = availaible REST services

$Response

Write-Host ""

# Query Accounts Example 
Write-Host "Accounts :"

$StrQuery = "SELECT Name, Id from Account LIMIT 100"

$URI = $Token.instance_url+"/services/data/v20.0/query?q=" + $StrQuery

$Response = Invoke-RestMethod -URI $URI -Method GET ` 
-Headers @{"Authorization" = "OAuth " + $Token.access_token};

Write-Host ""
Write-Host " # of Records : "
$Response.records.Count

Write-Host ""
Write-Host "Enum Account Name :"
$Response.records | % {$_.name}


# Query Opporunities Example 
$StrQuery = "SELECT AccountId, OwnerId, Name, Description, ` 
StageName, Amount, Probability FROM Opportunity WHERE StageName <> `</pre>
<pre>'Closed Lost' ORDER BY StageName "

$URI = $Token.instance_url+"/services/data/v20.0/query?q=" + $StrQuery

$Response = Invoke-RestMethod -URI $URI -Method GET ` 
-Headers @{"Authorization" = "OAuth " + $Token.access_token};

$Response.records.Count

Write-Host ""
Write-Host "Query Output :"

Foreach ($objItem in $Response.records) {

    "{0,-120} {1, 25} {2, 30}" -f `
 
   $objItem.name, $objItem.StageName, $objItem.Amount
 }

This script will return your Access Token, using this function

Get-AuthorizationTokenWithUsernamePasswordFlow

image

Next it will list the REST API’s you can use

image

Query Accounts Example :

image

Enjoy !

Smile

8 Responses to SalesForce.com – Accessing using Web Services and Scripting – Part 3

  1. Navan Mehra says:

    Thanks for sharing the details. When trying the same steps you mentioned above, I get 400 Bad Request error when I try to query the api after login. I received the access token and when appending it to header and querying, i receive Bad request error

  2. Andrew K says:

    Hi… Thank you for the great article, It helped me a lot.
    I have a query, I’m hoping you only can resolve it.

    I’m trying to fetch all the metadata from salesforce which was modified by the particular user based on userID using the following query.

    “SELECT CreatedById,CreatedDate,Display,Id FROM SetupAuditTrail WHERE CreatedById=”1234”

    I’m able to list all the records but now I want to retrieve filename instead of ID. I have checked the documentation but no luck.
    Please help me to resolve it.
    Thank you

    Andrew Kramer

    • Hi Andrew,

      I have to disappoint you, at the moment I don’t have access anymore to SF.com.
      So there is no way I can try to help out here?

      If I run into some blogpost I will definitely let you know !

      • Andrew K says:

        Ok, no issues. Than you for the quick response.
        If I get any solution, I’ll update you.
        Thanks

  3. Andrew says:

    Hey man.. The last couple of days the script was running perfectly but today when I tried again it was given me an error message.
    below is the error message..

    Invoke-RestMethod : The remote server returned an error: (400) Bad Request

    Please response.

    • Andrew K says:

      Issues resolved, FYI
      It was showing 400 error because of the password I used, It was containing a $ in it. If you want to know why $ was causing the issue simply google it.
      You’ll get the answer, So I changed my password and tried again.
      It worked.

  4. Thanks for the update !

  5. Andrew K says:

    Is there any way to store these values as k key-value pairs in XML format or as a dictionary.?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: