0

I am writing code, in order to test a flask REST server.

One of the responses of the server is:

return make_response(json.dumps({'myName': userName}), 200)

I can have access to the response's status code with:

response.status_code

But how do i have access to the myName parameter of the server's response?

pavelsaman
  • 7,399
  • 1
  • 14
  • 32
user1584421
  • 3,499
  • 11
  • 46
  • 86

1 Answers1

1

This question has very little to do with Pytest. All you're doing is parsing a JSON body into a dictionary and accessing its properties. That's all doable with requests library and Python itself.

I recommend reading requests documentation here, the first code block is enough in your example.

So a solution for your problem is:

import requests

my_name_property = requests.get("server_url").json()["myName"]

or in more steps:

import requests

response = requests.get("server_url")
response_body = response.json()
my_name_property = response_body["myName"]

You can't use response.myName, that's not how you access properties of a dictionary in Python. This would work with e.g. namedtuple in Python, or in Javascript. But not in Python when using dictionaries, which is what json() method returns in the examples above.

If something doesn't work, I recommend using Postman or any other such client to figure out what's going on on the API, how to call it, what response you get, in what structure, and once you understand it, write some tests in Python.

pavelsaman
  • 7,399
  • 1
  • 14
  • 32