Can´t import "ApplicationsRequestBuilder" method in python using Azure SDK

166 Views Asked by At

Following the official documentation, to list app registrations que must use "ApplicationsRequestBuilder", but there is no info about how to import it.

My imports are:

import pyodbc
import adal
import struct
import json  
import subprocess 
import asyncio 
from azure.identity import ClientSecretCredential, DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from msgraph import GraphServiceClient
from msgraph.generated.models.password_credential import PasswordCredential
from msgraph.generated.applications.item.add_password.add_password_post_request_body import AddPasswordPostRequestBody

I´ve tried everything, but I´m not able to import it. The error is:

File "/azp/_work/1/s/Update_Expired_Service_Principals/sp_renewal.py", line 83, in get_sp_id
query_params = ApplicationsRequestBuilder.ApplicationsRequestBuilderGetQueryParameters(
NameError: name 'ApplicationsRequestBuilder' is not defined

My code is:

scopes = ['https://graph.microsoft.com/.default']   
conn, credential, credentials = get_token()

graph_client = GraphServiceClient(credential, scopes=scopes)
    
async def get_sp_id():
    query_params = ApplicationsRequestBuilder.ApplicationsRequestBuilderGetQueryParameters(
        filter = "displayName eq 'test'",
        count = True,
        top = 1,
    )

request_configuration = ApplicationsRequestBuilder.ApplicationsRequestBuilderGetRequestConfiguration(
    query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")

app_list = await graph_client.applications.get(request_configuration = request_configuration)
if app_list:
    app = app_list[0]
    sp_id = await graph_client.applications.by_application_id(app.id).get()
    print(sp_id)
    return sp_id
return None
2

There are 2 best solutions below

0
gjgjgjgj14 On BEST ANSWER

To avoid this error is required to add:

from msgraph.generated.applications.applications_request_builder import ApplicationsRequestBuilder
0
Sridevi On

In my case, I have below app registrations with display name as 'test' :

enter image description here

To get objectID of these app registrations, you can make use of below sample Python code:

import asyncio
from azure.identity import ClientSecretCredential
from msgraph import GraphServiceClient

tenant_id = "tenantId"
client_id = "appId"
client_secret = "secret"

credential = ClientSecretCredential(
    tenant_id=tenant_id,
    client_id=client_id,
    client_secret=client_secret
)

client = GraphServiceClient(credential)

async def main():
    target_app = "test"

    result = await client.applications.get()
    applications = result.value

    filtered_applications = [app for app in applications if app.display_name == target_app]

    for app in filtered_applications:
        print(app.id)

asyncio.run(main())

Response:

enter image description here