2016-02-18 39 views
1

我正在尝试使用Azure ARM REST API。考虑一个例子,以创建资源组,这是蔚蓝的文件中提到的API使用Azure资源管理器REST API

https://management.azure.com/subscriptions/{subscription-id}/resourcegroups/{resource-group-name}?api-version={api-version} 

我的代码:

import httplib, urllib, base64 

headers = { 
    # Request headers 
    'Content-Type': 'application/json', 
    'Ocp-Apim-Subscription-Key': 'xxxxxx', 
    'Authorization': 'xxxxx', 
    'Identifier' : 'xxxxx' 
} 

params = urllib.urlencode({ 
"location":"Central US" 
}) 

try: 
    conn = httplib.HTTPSConnection('xxxx.azure-api.net') 
    conn.request("PUT", "/resourcegroups/resourcename?api-version=2015-01-01%s" % params, "{body}", headers) 
    response = conn.getresponse() 
    data = response.read() 
    print(response.status) 
    conn.close() 
except Exception as e: 
    print("[Errno {0}] {1}".format(e.errno, e.strerror)) 

我得到一个404错误。你能帮我找出我出错的地方吗?谢谢。

+0

难道你没有忘记你从文档中找到的URI中的/ subscriptions/{subscription-id}部分吗? – jakobandersen

+0

@miracledev,因为我知道'Ocp-Apim-Subscription-Key'参数是 –

+0

@MichaelB你确定它适用于资源管理器REST API吗?不是一个API管理功能? – jakobandersen

回答

0

基于我的理解,我认为你的代码中存在一些错误,如下所示。

  1. the package httplib API reference的REST API的URL应该被分成了hostpath & query string(或params)作为参数的函数httplib.HTTPSConnection & conn.request,如@ miracledev的评论说。所以响应状态是404没有找到。
  2. 功能conn.request的HTTP请求也是缺少该Common parameters and headers &的REST API的location required headerheadersAuthorization报头的内容从authenticating Azure Resource Manager request得到。

enter image description here

希望它能帮助。最好的祝福。

+0

嗨,我已经改变了我的标题和conn.request,正如你所提到的。现在我的头文件包含cotent-type,client_id,tenant_id和authentication_key。 conn.request就是这样。 conn.request(“GET”,“/ subscriptions/xxxx/resourcegroups/rapidresource?api-version = 2015-01-01%s”%params“,{ body}“,标题)。但现在它抛出401授权错误。我的标题部分是否还有其他参数? – shwetha

+0

@shwetha头文件应包含您可以在REST API文档中找到的必需元素。 'client_id','tenant_id'和'authentication_key'用于请求头部'Authorization'中使用的访问令牌,请关注文档https://msdn.microsoft.com/en-us/library/azure /dn790557.aspx。 –

+0

好的,我做了'pip install adal'并传递了这些参数来获得访问令牌。然后我在标题部分使用它。但它仍然给我一个401错误。 – shwetha