Prevent my flask app using html unicode for curly braces

76 Views Asked by At

I am making an API call in my flask app:

count = len(bankid)
bankid = "044"
response = requests.get(f"{base_api_url}/banks/" + "{bankid}/branches".format(bankid=f"{{{bankid}:0{count}d}}", headers=headers))

My target is to use this url https://api.flutterwave.com/v3/banks/044/branches. Passing in "044" string only removes the leading zero so trying to use python string formatting to pass in {044:03d}.

This is what I get:

GET /v3/banks/%7B044:03d%7D/branches HTTP/1.1" 401 65]

I want:

GET /v3/banks/044/branches HTTP/1.1" 401 65]

I want python to use "{}" rather than the unicode representation.

2

There are 2 best solutions below

6
On BEST ANSWER

There's no point of having bankId a string and then tell fstring to treat it as int just to enforce formatting that would produce it back in the form of original string. You are simply over-complicating the way you construct target URL:

bankid = "044"
response = requests.get(f"{base_api_url}/banks/{bankid}/branches", headers=headers)

EDIT

The bankid has to be an int32 not string and when I pass it as into python strips the leading zero

Then you should have make it clear in your question first. Anyway, the change is trivial, just create string form of bankId as you like prior using it:

bankid = 44
bankIdStr = str(bankId).zfill(3)  # change 3 to your liking
response = requests.get(f"{base_api_url}/banks/{bankidStr}/branches", headers=headers)
3
On

Formatting

In terms of formatting, this should be enough for keeping any leading zeroes (in a string):

some_string_id = '044'
url = f'{base_api_url}/banks/{some_string_id}/branches'
response = requests.get(url, headers=headers)

API reference

But from the API perspective it seems that what expected is id of a bank which is integer, not the code which is string and may as well have leading zeros. Make sure you pass an id. E.g.:

# "id": 191,
# "code": "044",
# "name": "Access Bank"

bank_id = 191
url = f'{base_api_url}/banks/{bank_id}/branches'
response = requests.get(url, headers=headers)