If you have this word in the curl response, print "OK"

1

I made a curl in python to check some information from my client, it's happening okay, the answer from my api is json, I would like to know how to do if api has, for example "userId", it shows itself an "OK" on the console.

 import requests


url = "https://minhaapi.com/v1/login/username"

querystring = {"countryCode":"BR"}

payload = "username=user&password=teste123&clientVersion=2.4.9-undefined"
headers = {
    'Content-Type': "application/x-www-form-urlencoded",
    'x-requested-with': "XMLHttpRequest",
    'x-tidal-token': "wdgaB1CilGA-S_s2"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)



Resposta da minha API(Quando o usuário loga com as informações no curl): 



{"userId":57261722,"sessionId":"5b1ada5b-addf-4804-a55e-a12f36959ff1","countryCode":"BR"}

I tried this code but could not:

for url in response.text:
        if 'userId' in url.lower():
            print ("OK")

I just want you to print on the "OK" screen when the curl shows the response in json above (that is when the user logs in), and if a different message appears, print "Error"     

asked by anonymous 18.05.2018 / 00:05

1 answer

1
for url in response.text:
        if 'userId' in url.lower():
            print ("OK")

Here you see if userId is in url.lower() . This will never result in True because I in userId is uppercase, and you compare this to the lowercase version of url .

url will not be a string either; response.text is a string, and when iterates over a string with a for , you get individual characters. I recommend that you try to print(url) before if to get an idea of what is happening.

Since your API returns a JSON, you do not have to deal with response.text , you can use the .json() method to turn the answer into a Python dictionary. From here, you can check that userId is a key in the dictionary:

if 'userId' in response.json():
    print('OK')
else:
    print('ERRO')

You should also use a dictionary to pass your payload, not a string:

payload = {'username': 'user',
           'password': 'teste123',
           'clientVersion': '2.4.9-undefined'}
    
18.05.2018 / 00:33