0

How can I call post API with python using more than one or none values coming from DB instead of hard coding the values in my payload? Meaning whenever I call post API, the payload value [id] can change according to the id or ids generated from SQL query. When I hard code it and pass one value at the time in my payload it works:

dictionary={"profile_fields": {"name":["email", "address"]},"filters": {"id": "AB1"}}

But when I don't want to hard code it and use the variable name used to query my DB instead, I don't get any result back nor do I see any error.

dictionary={"profile_fields": {"name": ["email","address"]},"filters": {"id": 
               df}}

Thank you for your help.

Sql output example:

col1:
AB1
AB2

Code sample Python 3:

 c = con.cursor()

# sql query from sqlite, the output can be 1 vaue or two or even empty
c.execute('select col1 from t1 where col1 = col2')

df=c.fetchall()

print('checking the output of sql',df)

 #print output:
  # [('AB1',), ('AB2',)]

# data payload
dictionary={"profile_fields": {"name": ["email", "address"]},"filters": {"id": df}}

# url
url='https://...'
#post api call
response= response.post(url,json=dictionary,...)

 
if (responce.status_code == 200):
   #response back in JSON format
   df = response.json()
   print('Success!')
else:
  print('error.. ')

1 Answer 1

0

I don't get any result back nor do I see any error

This is strange, because result of pd.read_sql_query is a dataframe, while fetchall is a method of cursor. I am pretty sure it should not be there, and calling it would raise an exception.

Next thing, df is a dataframe, and is probably 2-dimensional, because you did not specify column in read_sql_query. Thus, you are sending array of arrays of ids. Try printing the payload to see what is being sent:

print(json.dumps(dictionary))

Convert df to a collection of ids:

ids = tuple(df[0])

Now, ids may be empty, it may be one or many values. How you deal with that is not in the scope of this question, but for now you can just id = ids[0] and put it into dictionary (instead of df).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Shadows. For simplicity I just removed data frame and used execute sql query instead. The main problem with my code is when my query returns more than one value, the post api call doesn't work. I did print the output of query and even seen the payload in my debug with two Ids passed on. But where I'm struggling is how to pass these two values or more to call post api.
@Joe if API you're communicating with does not support multiple ids then there is just no way to do this in one request. Try iterating over ids, doing 1 request per id.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.