km457
km457

Reputation: 125

Using a Variable in REQUESTS in Python

I've got an API request to make that involves passing some variables from user input and a config file to a filter expression contained in a dictionary.

The API uses hashes in its structure to wrap stings by default, although I can specify another string wrapping indicator if need be via a separate request. As is, what I need to do is below, basically.

I can't figure out the syntax to get those strings to populate the values between the wrapper # signs. Lots of questions about this, but none addressing the basic syntax without additional functionality, as far as I can tell.

import config
import requests

var1 = **the result of user input, a string**
var2 = **a value from a config file, also a string**

url = (config.api_url)
payload = {
'key':config.api_key,
'Operation':'GetEntities',
'Entity':'my_entity',
'Attributes':'my_attribute1,my_attribute2',
'Filter':'api_var1<eq>#var1# AND api_var2<eq>#var2#'}

response = requests.post(url,payload)

They key point is here:

'Filter':'api_var1<eq>#var1# AND api_var2<eq>#var2#'

So if var1 = '1234' and var2 = '4321' I need it to be the equivalent of:

'Filter':'api_var1<eq>#1234# AND api_var2<eq>#4321#'

Upvotes: 0

Views: 4209

Answers (1)

Andersson
Andersson

Reputation: 52665

As far as I understand you want something like

'Filter':'api_var1<eq>#{0}# AND api_var2<eq>#{1}#'.format(var1, var2)}

or

'Filter':'api_var1<eq>#%s# AND api_var2<eq>#%s#' % (var1, var2)}

Upvotes: 3

Related Questions