How to create reports with Python SDK Api

Question:

I am trying to create reports with Python on dailymotion but I have error,According to my received error, renponse is empty. I don’t get it. I guess, My user coudln’t login to dailymotion. Please check error.

{‘data’: {‘askPartnerReportFile’: None}, ‘errors’: [{‘message’: ‘Not authorized to access `askPartnerReportFile` field.’, ‘path’: [‘askPartnerReportFile’], ‘locations’: [{‘line’: 3, ‘column’: 9}], **’type’: ‘not_authorized**’}]}
Traceback (most recent call last):

File "get_reports.py", line 143, in <module>
product=’CONTENT’,

File "get_reports.py", line 65, in create_report_request
return response.json()[‘data’][‘askPartnerReportFile’][‘reportFile’][‘reportToken’];

TypeError: ‘NoneType’ object is not subscriptable

Here is my code;

`

    
    def get_access_token(app_key, app_secret, username, password):
        '''
        Authenticate on the API in order to get an access token
        '''
        response = requests.post('https://graphql.api.dailymotion.com/oauth/token', data={
            'client_id': app_key,
            'client_secret': app_secret,
            'username': username,
            'password': password,
            'grant_type': 'password',
            'version': '2'
        })
    
        if response.status_code != 200 or not 'access_token' in response.json():
            raise Exception('Invalid authentication response')
    
        return response.json()['access_token']
    
    def create_report_request(access_token, dimensions, metrics, start_date, end_date, product, filters = None):
        '''
        Creating a report request
        '''
        reportRequest = """
        mutation ($input: AskPartnerReportFileInput!) {
            askPartnerReportFile(input: $input) {
                reportFile {
                    reportToken
                }
            }
        }
        """
        response = requests.post(
            'https://graphql.api.dailymotion.com',
            json={
                'query': reportRequest,
                'variables': {
                    'input': {
                        'metrics': metrics,
                        'dimensions': dimensions,
                        'filters': filters,
                        'startDate': start_date,
                        'endDate': end_date,
                        'product': product,
                    }
                }
            },
            headers={'Authorization': 'Bearer ' + access_token}
        )
        print(response.status_code)
        if response.status_code != 200 or not 'data' in response.json():
            raise Exception('Invalid response')
        print(response.json())
        return response.json()['data']['askPartnerReportFile']['reportFile']['reportToken'];
    
    def check_report_status(access_token, report_token):
        '''
        Checking the status of the reporting request
        '''
        report_request_status_check = """
        query PartnerGetReportFile ($reportToken: String!) {
            partner {
                reportFile(reportToken: $reportToken) {
                    status
                    downloadLinks {
                        edges {
                            node {
                                link
                            }
                        }
                    }
                }
            }
        }
        """
        response = requests.post(
            'https://graphql.api.dailymotion.com',
            json={
                'query': report_request_status_check,
                'variables': {
                    'reportToken': report_token
                }
            },
            headers={'Authorization': 'Bearer ' + access_token}
        )
    
        if response.status_code != 200 or not 'data' in response.json():
            raise Exception('Invalid response')
    
        status = response.json()['data']['partner']['reportFile']['status'];
    
        if (status == 'FINISHED'):
            download_links = []
            for url in map(lambda edge: edge['node']['link'], response.json()['data']['partner']['reportFile']['downloadLinks']['edges']):
                download_links.append(url)
            return download_links
        else:
            return None
    
    def download_report(download_links, base_path=None):
        '''
        Downloading the report files
        '''
        cpt = 1
        if not base_path:
            base_path = os.getcwd()
    
        for url in download_links:
            r = requests.get(url)
            filename = 'report_{}.csv'.format(cpt)
            file_path = os.path.join(base_path, filename)
            open(file_path, 'wb').write(r.content)
            print('Report file {} downloaded: {}'.format(cpt, file_path))
            cpt += 1
    
    print('Generating access token...')
    access_token = get_access_token(
        app_key='******',
        app_secret='*******',
        username='*****',
        password='*****'
    )
    
    print('Creating report request...')
    report_token = create_report_request(
        access_token=access_token,
        dimensions=('DAY', 'VIDEO_TITLE'),
        metrics=('VIEWS'),
        filters={'videoOwnerChannelSlug': 'B******'},
        start_date='2022-11-23',
        end_date='2022-11-24',
        product='CONTENT',
    )
    
    download_links = None
    while not download_links:
        print('Checking report status...')
        # Checks every 15secs the report status
        time.sleep(15)
        download_links = check_report_status(
            access_token=access_token,
            report_token=report_token
        )
    
    download_report(download_links=download_links)

`

I tried to get data dailymotion api.

Thanks

Asked By: Ali Poyraz

||

Answers:

This feature requires a specific API access, which is missing on your API Key, that’s why you get the message Not authorized to access askPartnerReportFile field.

As it’s a feature restricted to verified-partners, you should reach out to your content manager to ask him this kind of access, or you can try to contact our support

Answered By: dailymotion
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.