azureazure-powershellazure-cli2

AZ REST DevOps method returns "az : Not a json response"


I'm running powershell on a windows 10 machine There is trouble running AZ REST method. This script works and was even working with the user account where its now failing and I don't know why. Here is the core function making the AZ REST call.

function getreleasedefinitionrequest($definitionid, $org, $project)
{
    $requestpath = "/_apis/release/definitions/" + $definitionid + "?api-version=6.0-preview.4"
    $tokeninfo = az account get-access-token | convertfrom-json
    $token = $tokeninfo.accessToken
    $uribase = "https://vsrm.dev.azure.com/" + $org + "/" + $project
    $uri = $uribase+$requestpath
    $authheader = "Authorization=Bearer " + $token
    $result = az rest --uri $uri --headers $authheader | convertfrom-json
    return $result
}

To ensure I'm using an account that has permissions, I'm explicitly logging out and then back in as shown

Az logout –username ‘emailusername’
Clear-AzContext
Connect-AzAccount 
az login --only-show-errors --allow-no-subscriptions 

Running the AZ REST line of script produces an error

> az : Not a json response, outputting to stdout. For binary data
> suggest use "--output-file" to write to a file At line:1 char:1
> + az rest --uri $uri --headers $authheader
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>     + CategoryInfo          : NotSpecified: (Not a json resp...write to a file:String) [], RemoteException
>     + FullyQualifiedErrorId : NativeCommandError   The command failed with an unexpected error. Here is the traceback: 'charmap' codec can't
> encode character '\u221e' in position 6302: character maps to
> <undefined> Traceback (most recent call last):   File
> "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py",
> line 18, in rest_call   File
> "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\requests\requests\models.py",
> line 897, in json   File "C:\Program Files (x86)\Microsoft
> SDKs\Azure\CLI2\lib\json\__init__.py", line 354, in loads
>     return _default_decoder.decode(s)   File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 339, in
> decode
>     obj, end = self.raw_decode(s, idx=_w(s, 0).end())   File "C:\Program Files (x86)\Microsoft
> SDKs\Azure\CLI2\lib\json\decoder.py", line 357, in raw_decode
>     raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char
> 4).....

Setting the output to a file doesn't help solve this problem. The output is included below as well.

Thoughts on what is going wrong with this call?

--interesting snippets from the debug output (org and project names changed to protect the innocent)

PS C:\> az rest --uri $uri --headers $authheader --debug
az : Command arguments: ['rest', '--uri', 'https://vsrm.dev.azure.com/bugs/bunny/_apis/release/definitions/25?api-version=6.0-preview.4', '--headers', 
'Authorization=Bearer {a valid token here}, '--debug']
At line:1 char:1
+ az rest --uri $uri --headers $authheader --debug
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Command argumen...Bg', '--debug']:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 

Found a match in the command table for 'rest'
Event: CommandInvoker.OnPreCommandTableTruncate [<function AzCliLogging.init_command_file_logging at 0x0432B978>]
...
Request method: 'GET'
Request headers:
    'User-Agent': 'AZURECLI/2.9.1 (MSI)'
    'Accept-Encoding': 'gzip, deflate'
    'Accept': '*/*'
    'Connection': 'keep-alive'
    'Authorization': 'Bearer eyJ0eXAiOiJKV...'
    'x-ms-client-request-id': '28123a14-8d60-4263-95a6-b7634ad14fae'
    'CommandName': 'rest'
    'ParameterSetName': '--uri --headers --debug'
Request body:
None
urllib3.connectionpool : Starting new HTTPS connection (1): vsrm.dev.azure.com:443
urllib3.connectionpool : https://vsrm.dev.azure.com:443 "GET /bugs/bunny/_apis/release/definitions/25?api-version=6.0-preview.4 HTTP/1.1" 302 638
urllib3.connectionpool : Starting new HTTPS connection (1): spsprodeus24.vssps.visualstudio.com:443
urllib3.connectionpool : https://spsprodeus24.vssps.visualstudio.com:443 "GET /_signin?realm=vsrm.dev.azure.com&reply_to=https%3A%2F%2Fvsrm.dev.azure.com%2Fbugs%2Fbunny%2F_apis%2Frelease%2Fdefinitions%2F25%3Fapi-version%3D6.0-preview.4&redirect=1&hid=6f3eb511-31e9-4467-8450-015b9e4c36d7&force=1&context=eyJodCI6MiwiaGlkIjoiNWN
lYzEyNTYtYzgyNi00YmYwLWEzN2YtMDMzY2RlZDZjOTdkIiwicXMiOnt9LCJyciI6IiIsInZoIjoiIiwiY3YiOiIiLCJjcyI6IiJ90 HTTP/1.1" 203 15761
Response status: 203
Response headers:
    'Cache-Control': 'no-cache, no-store, must-revalidate'
    'Pragma': 'no-cache'
    'Content-Length': '15761'
    'Content-Type': 'text/html; charset=utf-8'
    'Expires': '-1'
    'P3P': 'CP="CAO DSP COR ADMa DEV CONo TELo CUR PSA PSD TAI IVDo OUR SAMi BUS DEM NAV STA UNI COM INT PHY ONL FIN PUR LOC CNT"'
 ....
Response content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    
<html lang="en-US">
<head><title>
    
            Azure DevOps Services | Sign In
        
</title><meta http-equiv="X-UA-Compatible" content="IE=11;&#32;IE=10;&#32;IE=9;&#32;IE=8" />
    <link rel="SHORTCUT ICON" href="/favicon.ico"/>
    <link data-bundlelength="508967" data-bundlename="commoncss" 
data-highcontrast="/_static/tfs/M175_20200921.1/_cssbundles/HighContrast/vss-bundle-commoncss-vbprQZmxiRGQT6OOu7QI7gB_rewyS40Ce_ulm1Fh3rQQ=" 
data-includedstyles="jQueryUI-Modified;Core;Splitter;PivotView" 
href="/_static/tfs/M175_20200921.1/_cssbundles/Default/vss-bundle-commoncss-v18eOGnLpZpVm7mtRF63HJdB9wzrq2LZpAxko9qNRfdY=" rel="stylesheet" />
<link data-bundlelength="116298" data-bundlename="viewcss" 
data-highcontrast="/_static/tfs/M175_20200921.1/_cssbundles/HighContrast/vss-bundle-viewcss-vEVbIBXjzIJjwNr9KLU5WDHxT9Mx0Vzbs0OoptSmlcL0=" 
data-includedstyles="VSS.Controls" href="/_static/tfs/M175_20200921.1/_cssbundles/Default/vss-bundle-viewcss-vy_tKROQBdqLPOEEYAX4_J3xujP2C8V_PKfv97xulJp4=" rel="stylesheet" 
/>
    <!--UxServices customizations -->
    
    <link href="/_static/tfs/M175_20200921.1/_content/Authentication.css" type="text/css" rel="stylesheet" />
    
</head>
<body class="platform">
    <script type="text/javascript"> var __vssPageContext = 
....

<script type="text/javascript">if (window.performance && window.performance.mark) { window.performance.mark('endLoadBundleOuter-basejs'); }</script>
<script type="text/javascript"> require.config(__vssPageContext.moduleLoaderConfig);</script>
    <input name="__RequestVerificationToken" type="hidden" value="VBtc64BwCvt771roAgRwaemm_A9O3oDLlv1IBcNtee3hQFIK_0JwwQKAPDld6FUF3yuOOQPu98NQHsnD6ClR8SM5cs81" /><input 
name="__RequestVerificationToken2" type="hidden" value="__RequestVerificationToken29e00bc5d-8f47-40f7-a563-08eba0d0aeff" />
    
    
    
    
    <div class="account signin main-container hide">
            <div class="page-content">
                <div class="header-section" role="banner">
                    
                    <link rel="stylesheet" type="text/css" href="/_static/tfs/M175_20200921.1/_content/Combined.css">
                    <div id="ux-header" class="FF ltr vsIntegrate" xmlns="http://www.w3.org/1999/xhtml">
                        <span id="isMobile"></span>
                        <div class="upperBand">
                            <div class="upperBandContent">
                                <div class="left"></div>
                                <div class="right">
                                    <div class="profileImage"></div>
                                    <div id="signIn">
                                        <a class=":SignedOutProfileElement: createProfileLink" href="/go/profile" title="Anonymous">Anonymous</a>
                                        <a class="scarabLink" href="/_signout">Sign out</a>
                                    </div>
                                </div>
                                <div class="clear-both"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="content-section" role="main">
                    
    
            <div class="signin-main-content">
                <noscript>
                    <span class="error">Microsoft Internet Explorer&#39;s Enhanced Security Configuration is currently enabled on your environment. This enhanced level of 
security prevents our web integration experiences from displaying or performing correctly. To continue with your operation please disable this configuration or contact your 
administrator.</span>
                </noscript>
                <div class="provider-control">                    
                    <script class="options" defer="defer" type="application/json">{"providerOptions":{"force":true,"orgIdAuthUrl":"https://login.microsoftonline.com/6c637512
-c417-4e78-9d62-b61258e4b619/oauth2/authorize?client_id=499b84ac-1321-427f-aa17-267ca6975798\u0026site_id=501454\u0026response_mode=form_post\u0026response_type=code+id_toke
n\u0026redirect_uri=https%3A%2F%2Fspsprodeus24.vssps.visualstudio.com%2F_signedin\u0026nonce=864655b9-45b2-4b3a-b583-bb1283556687\u0026state=realm%3Dvsrm.dev.azure.com%26rep
ly_to%3Dhttps%253A%252F%252Fvsrm.dev.azure.com%252Fbugs%252Fbunny%252F_apis%252Frelease%252Fdefinitions%252F25%253Fapi-version%253D6.0-preview.4%26ht%3D2%
26hid%3D6f3eb511-31e9-4467-8450-015b9e4c36d7%26force%3D1%26nonce%3D864655b9-45b2-4b3a-b583-bb1283556687\u0026resource=https%3A%2F%2Fmanagement.core.windows.net%2F\u0026cid=8
64655b9-45b2-4b3a-b583-bb1283556687\u0026wsucxt=1\u0026prompt=select_account","user":null,"signInContext":"eyJodCI6MiwiaGlkIjoiNWNlYzEyNTYtYzgyNi00YmYwLWEzN2YtMDMzY2RlZDZjOT
dkIiwicXMiOnsicmVhbG0iOiJ2c3JtLmRldi5henVyZS5jb20iLCJyZXBseV90byI6Imh0dHBzOi8vdnNybS5kZXYuYXp1cmUuY29tL3JlZG1ldGFsL2Nvbm5lY3RlZGNvbW11bml0aWVzL19hcGlzL3JlbGVhc2UvZGVmaW5pdGl
vbnMvMjU_YXBpLXZlcnNpb249Ni4wLXByZXZpZXcuNCIsImh0IjoiMiIsImhpZCI6IjZmM2ViNTExLTMxZTktNDQ2Ny04NDUwLTAxNWI5ZTRjMzZkNyIsImZvcmNlIjoiMSIsIm5vbmNlIjoiODY0NjU1YjktNDViMi00YjNhLWI1
ODMtYmIxMjgzNTU2Njg3In0sInJyIjoiIiwidmgiOiIiLCJjdiI6IiIsImNzIjoiIn01"}}</script>
                </div>
            </div>
                </div>
                 
    
    </div>
    
    
  ...
</body>
</html>
Not a json response, outputting to stdout. For binary data suggest use "--output-file" to write to a file
cli.azure.cli.core.util : The command failed with an unexpected error. Here is the traceback:
The command failed with an unexpected error. Here is the traceback:
cli.azure.cli.core.util : 'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
Traceback (most recent call last):
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 18, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\requests\requests\models.py", line 897, in json
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\knack\knack\cli.py", line 215, in invoke
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 654, in execute
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 718, in _run_jobs_serially
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 711, in _run_job
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\six\six.py", line 703, in reraise
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 688, in _run_job
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 325, in __call__
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\__init__.py", line 776, in default_command_handler
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 22, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 41, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 162, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 190, in write_and_convert
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 195, in write_plain_text
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
Traceback (most recent call last):
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 18, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\requests\requests\models.py", line 897, in json
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\knack\knack\cli.py", line 215, in invoke
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 654, in execute
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 718, in _run_jobs_serially
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 711, in _run_job
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\six\six.py", line 703, in reraise
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 688, in _run_job
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\commands\__init__.py", line 325, in __call__
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\core\__init__.py", line 776, in default_command_handler
  File "D:\a\1\s\build_scripts\windows\artifacts\cli\Lib\site-packages\azure\cli\command_modules\util\custom.py", line 22, in rest_call
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 41, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 162, in write
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 190, in write_and_convert
  File "C:\Users\VSSADM~1\AppData\Local\Temp\pip-install-yh2ypeu1\colorama\colorama\ansitowin32.py", line 195, in write_plain_text
  File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u221e' in position 6302: character maps to <undefined>
{truncated end of file}

Solution

  • According to the error, you do not provide the right access token. Because the Azure CLI az account get-access-token just can get access token to get Azure resource or Azure AD resources. It cannot be used to get Azure DevOps access token. For more details, please refer to here and here.

    If you want to use CLI to manage Azure DevOps, you can use Azure DevOps CLI. For example, if you want to get release definition, you can use the command az pipelines release definition show.


    Update

    if you want to use PAT to call Azure devops rest API, please refer to the following script

    $username =""
    $password="<your PAT>"
    $tokens = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
    
    
    $authheader = "Authorization=Basic " + $tokens 
    $res = az rest --uri "https://vsrm.dev.azure.com/jim0375/test/_apis/release/definitions?api-version=6.0" --headers  $authheader 
    $res
    

    enter image description here