News & Announcements User Community Developer Community

Welcome to the RingCentral Community

Please note the community is currently under maintenance and is read-only.

Search
Make sure to review our Terms of Use and Community Guidelines.
  Please note the community is currently under maintenance and is read-only.
Home » Developers
Cannot connect to RC api using powershell
Tags: rest api
Mar 25, 2024 at 10:23am   •   1 replies  •  0 likes
John Morrow

Cannot connect to API using my powershell script. It looks like it connects but then when it starts running through the AD portion of my script it errors out with this error:


t C:\PSAutomations\RCUpdateInfoV3-test.ps1:36 char:17
+ ... $userinfo = Get-ADUser -Filter "UserPrincipalName -eq '$email'" -prop ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 
Invoke-RestMethod : {
  "message": "Need Content-Type header"


Full Script:


$RC_SERVER_URL="https://platform.ringcentral.com"
$RC_CLIENT_ID="Yxxxxxx"
$RC_CLIENT_SECRET="xxxxxx"
$RC_JWT_TOKEN = "xxxxxxxx"

$headers = @{
    ContentType = 'application/x-www-form-urlencoded; charset=UTF-8'
    Accept = 'application/json'
    Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("${RC_CLIENT_ID}:${RC_CLIENT_SECRET}"))
}

# RC authenticate and obtain access token
$response = Invoke-RestMethod -Method POST -Uri ($RC_SERVER_URL + "/restapi/oauth/token") -Headers $headers -Body @{
    grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
    assertion = $RC_JWT_TOKEN
}

# Extyract Access Token
$access_token = $response.access_token

# Fetch User info from RC api
$AllUsers = Invoke-RestMethod ($RC_SERVER_URL + "/restapi/v1.0/account/~/extension/?perPage=1000") -Headers @{
    Authorization = "Bearer $access_token"
} -Method Get

# Array to store users with AD information
$UsersArray = @()

#import AD Module
Import-Module ActiveDirectory

# Iterating over user records
foreach ($id in $AllUsers.records) {
    $email = $id.contact.email
    # Retrieving AD user information using email
    $userinfo = Get-ADUser -Filter "UserPrincipalName -eq '$email'" -properties department, title
    $emailCheck = $userinfo.UserPrincipalName

    if ($emailcheck -ne $null -and $id.type -ne "Department") { 
        $department = $userinfo.department
        $jobtitle = $userinfo.title
      
        $UsersArray += @(
            @{
                id = $id.id
                email = $id.contact.email
                department = $department
                jobtitle = $jobtitle
            }
        )
    } 
}

# Iterating over users and updating profiles
foreach ($user in $UsersArray) {
    $did = $user.id
    $putbody = '{"contact": {"jobTitle":"' + $user.jobtitle + '"}}'
    Invoke-RestMethod ($RC_SERVER_URL + "/restapi/v1.0/account/~/extension/$did") -Headers @{
        Authorization = "Bearer $access_token"
        ContentType = 'application/json'  # Add Content-Type header
    } -Method PUT -Body $putbody
    
    $putdepartment = '{"contact": {"department":"' + $user.department + '"}}'
    Invoke-RestMethod ($RC_SERVER_URL + "/restapi/v1.0/account/~/extension/$did") -Headers @{
        Authorization = "Bearer $access_token"
        ContentType = 'application/json'  # Add Content-Type header
    } -Method PUT -Body $putdepartment

    Start-Sleep -Seconds 3
    $did = $null
}
1 Answer
answered on Mar 25, 2024 at 10:46am  

Try add the Content-Type and the Accept headers to each API request.

# Fetch User info from RC api
$AllUsers = Invoke-RestMethod ($RC_SERVER_URL + "/restapi/v1.0/account/~/extension/?perPage=1000") -Headers @{
    Content-Type = "application/json"
    Accept = "application/json"
    Authorization = "Bearer $access_token"
} -Method Get


 0
on Mar 25, 2024 at 11:44am   •  0 likes

Still getting same error after changing the code


below is an excerpt from the code with the changes you suggested.


# RC authenticate and obtain access token
$response = Invoke-RestMethod -Method POST -Uri ($RC_SERVER_URL + "/restapi/oauth/token") -Headers $headers -Body @{
    grant_type = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
    assertion = $RC_JWT_TOKEN
}

# Extyract Access Token
$access_token = $response.access_token

# Fetch User info from RC api
$AllUsers = Invoke-RestMethod ($RC_SERVER_URL + "/restapi/v1.0/account/~/extension/?perPage=1000") -Headers @{
    "Content-Type" = "application/json"
    "Accept" = "application/json"
    "Authorization" = "Bearer $access_token"
} -Method Get
on Mar 25, 2024 at 3:50pm   •  0 likes

Maybe you can try this

# Fetch User info from RC api
$AllUsers = Invoke-RestMethod ($RC_SERVER_URL + "/restapi/v1.0/account/~/extension/?perPage=1000") -Headers @{
    "Authorization" = "Bearer $access_token"
} -ContentType 'application/json' -Method Get

on Mar 26, 2024 at 7:30am   •  0 likes

Same issue again.... I am about to give up on Powershell and try this with Python. Would you have any suggestions on how to connect with JWT token using python?

on Mar 26, 2024 at 8:46am   •  0 likes

It would be much easy in Python as we have a RingCentral Python SDK.

Install the SDK

$ pip install ringcentral python-dotenv

Import and instantiate the SDK

from ringcentral import SDK

rcsdk = SDK('RC_CLIENT_ID, 'RC_CLIENT_SECRET, 'RC_SERVER_URL')

# Get the platform instance
platform = rcsdk.platform()

Authenticate a user with its JWT and call the APIs

def read_extensions():
    try:
        resp = platform.get("/restapi/v1.0/account/~/extension")
        jsonObj = resp.json()
        for record in jsonObj.records:
            ...
    
    except Exception as e:
        print (e.message)

def login():
    try:
      platform.login( jwt='RC_JWT' )
      read_extensions()
    except Exception as e:
      sys.exit("Unable to authenticate to platform. Check credentials." + str(e))

login()
on Mar 25, 2024 at 11:44am   •  0 likes
At C:\PSAutomations\RCUpdateInfoV3-test.ps1:60 char:5
+     Invoke-RestMethod ($RC_SERVER_URL + "/restapi/v1.0/account/~/exte ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Invoke-RestMethod : {
  "message": "Need Content-Type header"



A new Community is coming to RingCentral!

Posts are currently read-only as we transition into our new platform.

We thank you for your patience
during this downtime.

Try Workflow Builder

Did you know you can easily automate tasks like responding to SMS, team messages, and more? Plus it's included with RingCentral Video and RingEX plans!

Try RingCentral Workflow Builder

PRODUCTS
RingEX
Message
Video
Phone
OPEN ECOSYSTEM
Developer Platform
APIs
Integrated Apps
App Gallery
Developer support
Games and rewards

RESOURCES
Resource center
Blog
Product Releases
Accessibility
QUICK LINKS
App Download
RingCentral App login
Admin Portal Login
Contact Sales
© 1999-2024 RingCentral, Inc. All rights reserved. Legal Privacy Notice Site Map Contact Us