-2

I'm trying to interact with the Trakt.tv api, but i'm struggling in create a variable inside a string dictionary.

The api OAuth make a call to the server, that provides 2 access codes, one of those code need to be forwarded to a following server call. like this:

values = """{
    "code": "code provide by the api",
    "client_id": "code provide by user",
    "client_secret": "code provide by user"
  }
""" 
headers = {
  'Content-Type': 'application/json'
}
request = Request('https://api.trakt.tv/oauth/device/token', data=values, headers=headers)

I have the needed code in variable api_code and would like to put this variable inside the string, like the following example.

values = """{
    "code": f"api_code",
    "client_id": f"user_code",
    "client_secret": f"user_code_2"
  }
""" 
headers = {
  'Content-Type': 'application/json'
}
request = Request('https://api.trakt.tv/oauth/device/token', data=values, headers=headers)
Renan Lopes
  • 1,229
  • 2
  • 10
  • 17
  • Was just writing a longer answer when the question was closed, but don't put the variable in a string, instead use a real python dict and transform it via the [json](https://docs.python.org/3/library/json.html) module to valid json `data = {"code": api_code}; values = json.dumps(data)` – syntonym Jan 23 '19 at 18:08
  • Thanks. Worked perfectly! – Renan Lopes Jan 24 '19 at 10:20

1 Answers1

1

IIUC you can use .format() like this:

values = """{{
    "code": f"{0}",
    "client_id": f"user_code",
    "client_secret": f"user_code_2"
  }}
""" 

api_code = 'abc123'
values = values.format(api_code)

Note that in order to get actual {} characters in the format string, you need to double them as I have in lines 1 and 4 here

wpercy
  • 9,636
  • 4
  • 33
  • 45