Search code examples
pythonjsonokta-api

Python do nothing IF empty JSON object


I am a python noob looking for best practice advice and a resolution to this problem. I am able to successfully pull the data I require from the Okta API which results in the output "PRECONDITION FAILED. Errors reported by remote server: Failed to update. Resource changed on the server." thats only half of what I want. I would like to be able to check for that output every 60 minutes and if it doesnt exist do nothing. I thought thats what I was doing in code below in the "start" function but it doesnt seem to behave the way I want it to. How do I store json objects in the variable events or exit the app if the object doesnt appear? Thank you in advance!

import requests
import os
import json
import time
from datetime import datetime, timedelta

key = os.environ['OKTA_AUTH']
outcome = 'outcome.result eq "FAILURE"'
event_type = 'eventType eq "application.provision.user.deactivate"'
app_id = 'target.id eq "*******"'
all_params = f'{event_type} and {app_id} and {outcome}'
api_url = f'https://domain.okta.com/api/v1/logs'

last_hour_date_time = datetime.utcnow() - timedelta(minutes=60)
since = str(last_hour_date_time.strftime('%Y-%m-%dT%H:%M:%S.000Z'))

def auth_okta():
    url = api_url.format()
    print(url)
    params = {
        'filter': all_params,
        'since': since
    }
    response = requests.get(url, params=params,
                        headers={'Accept': 'application/json', 
                        'authorization': key})
    response_json = response.json()
    return response_json

def start():
    for event_data in auth_okta():
        events = event_data['outcome']['reason']
        if not events:
            print('nothing there')
        else:
            print(events)

start()


Solution

  • You can use sys.exit() to end all execution.

    if events == None:
        sys.exit(0)