2

I am new to Azure. I need to set up an automation script to list all Ips in azure using Azure Rest APi in Python. However i couldnt been able to get any result from the API url I am passing to the request.

I am following this https://learn.microsoft.com/en-us/rest/api/virtualnetwork/public-ip-addresses/list-all#code-try-0

In code block, I have tried using requests

import requests


apijson = requests.get("https://management.azure.com/subscriptions/9540b342-9f94-4dd9-9eca-0698dda0107c/providers/Microsoft.Network/publicIPAddresses?api-version=2021-05-01"

I know I need to setup Oauth/authentication but I don't know what I need to declare or pass any token from my script

seldesjo
  • 169
  • 1
  • 3
Umesh417
  • 75
  • 1
  • 8

1 Answers1

2

I know I need to setup Oauth/authentication but I don't know what I need to declare or pass any token from my script

You can declare/pass token, for example:

import sys
import requests
import json
import time

test_api_url = "Add URL which you want to test"


#function to obtain a new OAuth 2.0 token from the authentication server

def get_new_token():
    auth_server_url = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token'"
    client_id = 'XXXX-XXXX-XXXX'
    client_secret = 'XXXX'

    token_req_payload = {'grant_type': 'client_credentials'}

    token_response = requests.post(auth_server_url,
    data=token_req_payload, verify=False, allow_redirects=False,
    auth=(client_id, client_secret))
             
if token_response.status_code !=200:
            print("Failed to obtain token from the OAuth 2.0 server", file=sys.stderr)
            sys.exit(1)

            print("Successfuly obtained a new token")
            tokens = json.loads(token_response.text)
            return tokens['access_token']

token = get_new_token()

while True:

    api_call_headers = {'Authorization': 'Bearer ' + token}
    api_call_response = requests.get(test_api_url, headers=api_call_headers, 
    verify+False)


if  api_call_response.status_code == 401:
    token = get_new_token()
else:
    print(api_call_response.text)

time.sleep(30)

You can refer to How to authenticate and authorize Python applications on Azure, Azure AD Authentication Python Web API and Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Ecstasy
  • 1,866
  • 1
  • 9
  • 17