# UnboundLocalError: cannot access local variable 'api\_response'

**URL:** https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231
**Category:** Python Help
**Created:** [May 30, 2023, 11:51am UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231 "2023-05-30T11:51:35Z")
**Posts on this page:** 10
**Page:** 1

<div class="post-metadata">

### Author: ![peya02](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/peya02/32/12515_2.png) [@peya02](https://discuss.python.org/u/peya02)
#### Post date: [May 30, 2023, 11:51am UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/1 "2023-05-30T11:51:35Z")

</div>

Why does the error appear in the console but only with the last user registered in the database?  
The error appears when I login.

```auto
# UnboundLocalError
UnboundLocalError: cannot access local variable 'api_response' where it is not associated with a value

```

Before this error, I had two users registered in the database, they do not give me an error, it is only the last one recently registered that gives an error.

---

<div class="post-metadata">

### Author: ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)
#### Post date: [May 30, 2023, 12:29pm UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/2 "2023-05-30T12:29:40Z")

</div>

`UnboundLocalError` is raised when you try to use the value of a local variable before assigning to it:

```auto
>>> def foo():
... print(x)
... x = 'Hello'
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value

```

---

<div class="post-metadata">

### Author: ![peya02](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/peya02/32/12515_2.png) [@peya02](https://discuss.python.org/u/peya02)
#### Post date: [May 30, 2023, 12:53pm UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/3 "2023-05-30T12:53:53Z")

</div>

And why does it work with two users and not with the latter?

---

<div class="post-metadata">

### Author: ![Axe319](https://avatars.discourse-cdn.com/v4/letter/a/e99b99/32.png) [@Axe319](https://discuss.python.org/u/Axe319)
#### Post date: [May 30, 2023, 1:09pm UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/4 "2023-05-30T13:09:12Z")

</div>

We would need to see the code in question that is producing the error to answer that without guessing.

---

<div class="post-metadata">

### Author: ![peya02](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/peya02/32/12515_2.png) [@peya02](https://discuss.python.org/u/peya02)
#### Post date: [May 31, 2023, 5:02am UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/5 "2023-05-31T05:02:23Z")

</div>

I attach this to see if it works for you but I attach code. What specific file would you need?

 ![image](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/6/609a9ee68ec287ea83644aa196710447fccd5713.png)

What is curious is that the same code works for two users and not for a third…

---

<div class="post-metadata">

### Author: ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)
#### Post date: [May 31, 2023, 5:21pm UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/6 "2023-05-31T17:21:55Z")

</div>

Judging by the last message, it’s in the function `all_reports` in `C:\Flask\APP-POWERBY\src\embedded.py`.

Oh, and it would’ve saved me having to retype it from an image if you’d copied and pasted the traceback as text!

---

<div class="post-metadata">

### Author: ![peya02](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/peya02/32/12515_2.png) [@peya02](https://discuss.python.org/u/peya02)
#### Post date: [June 1, 2023, 11:19am UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/7 "2023-06-01T11:19:46Z")

</div>

```auto
def all_workshop2(app,db,id):
    url='https://api.powerbi.com/v1.0/myorg/groups'
    api_response = requests.get(url, headers=get_request_header(app,db,id))
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    #print(api_response)
    api_response['value']

    return (api_response['value'])

def all_reports(app,db,workshop,id):
    reportes=[]
    # print(session)
    # print(workshop)
    for i in workshop:
        if i['type'] == 'Workspace':
            url=f"https://api.powerbi.com/v1.0/myorg/groups/{i['id']}/reports"
            api_response = requests.get(url, headers=get_request_header(app,db,id))
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    print(api_response['value'])
    for a in api_response['value']:
        dic2={'id_workshop':i['id'],'id_report':a['id'], 'name_report':a['name'] }
        reportes.append(dic2)
    return (reportes)

def get_request_header():
        '''Get Power BI API request header

        Returns:
            Dict: Request header
        '''

        return {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + AadService.get_access_token()}

```

---

<div class="post-metadata">

### Author: ![Axe319](https://avatars.discourse-cdn.com/v4/letter/a/e99b99/32.png) [@Axe319](https://discuss.python.org/u/Axe319)
#### Post date: [June 1, 2023, 2:10pm UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/8 "2023-06-01T14:10:21Z")

</div>

It looks like `api_response` is only defined conditionally.  
Specifically, `if i['type'] == 'Workspace'`.

The error you’re seeing is a direct result of that condition not being met, or the iterable `workshop` not returning any values.  
When the line `if api_response.status_code != 200:` is executed, `api_response` has not been defined yet.

You can correct this by initially setting `api_response` to `None` and then doing an early `return` prior to the status code check if it’s value is still `None`.

Something similar to this should work:

```auto
def all_reports(app,db,workshop,id):
    reportes=[]
    api_response = None
    for i in workshop:
        if i['type'] == 'Workspace':
            url=f"https://api.powerbi.com/v1.0/myorg/groups/{i['id']}/reports"
            api_response = requests.get(url, headers=get_request_header(app,db,id))
    if api_response is None:
        return []
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    print(api_response['value'])
    for a in api_response['value']:
        dic2={'id_workshop':i['id'],'id_report':a['id'], 'name_report':a['name'] }
        reportes.append(dic2)
    return (reportes)

```

---

<div class="post-metadata">

### Author: ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)
#### Post date: [June 1, 2023, 4:09pm UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/9 "2023-06-01T16:09:43Z")

</div>

@Axe319 is correct.

It’s also an opportunity to use the `for...else` construct, if you’re so inclined:

```auto
def all_reports(app,db,workshop,id):
    reportes=[]
    for i in workshop:
        if i['type'] == 'Workspace':
            url=f"https://api.powerbi.com/v1.0/myorg/groups/{i['id']}/reports"
            api_response = requests.get(url, headers=get_request_header(app,db,id))
            break
    else:
        return []
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    print(api_response['value'])
    for a in api_response['value']:
        dic2={'id_workshop':i['id'],'id_report':a['id'], 'name_report':a['name'] }
        reportes.append(dic2)
    return (reportes)

```

---

<div class="post-metadata">

### Author: ![peya02](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/peya02/32/12515_2.png) [@peya02](https://discuss.python.org/u/peya02)
#### Post date: [June 2, 2023, 5:27am UTC](https://discuss.python.org/t/unboundlocalerror-cannot-access-local-variable-api-response/27231/10 "2023-06-02T05:27:10Z")

</div>

Thank you very much, I will try it and report results.
