Home > Blockchain >  how do you check different api calls until it is succesful in python
how do you check different api calls until it is succesful in python

Time:01-19

I have a server list:

hosts=['server1','server2','server3','server4']

there are server 4 monitoring tools accessed by api calls. these monitoring env urls basically the same except for each env has unique id which is part of the url. These servers can be on any of the 4 monitoring tools. I need to find out which url these servers belong to.

for example, these are the monitoring tools urls:

production_env="https://example.com/e/envid123"
dev_env="https://example.com/e/envid678"
test_env="https://example.com/e/envid567"
uat_env="https://example.com/e/envid1000"

given the server name, I need to find out which env they belong to.

given a server name, for example "server1",

api url would become https://example.com/e/envid123&serverName="server1", this url will give whether server1 exists in production_env or not. I need to check each env url until I find the given server.

I am trying something like this:

envId=['envid123','envid678','envid567','envid1000']

for server in hosts:
   for id in envId:
    url="https://example.com/e/" id &serverName=server
    resp=request.get(url)

Any ideas how could do this the best way?

CodePudding user response:

You need quotes around &serverName= to concatenate them. But it's simpler to use a formatting method, such as f-strings.

To find the desired URL, use resp.json to get the decoded JSON, and check the value of the appropriate dictionary element.

found = False
for server in hosts:
    for id in envId:
        url = f"https://example.com/e/{id}&serverName={server}"
        resp = request.get(url)
        if resp.json['totalCount'] > 0:
            found = True
            print(f"Success at host = {server} id = {id}")
            break
    if found:
        break
else:
    print("No server found")
  •  Tags:  
  • Related