Say I have two REST API endpoints (http://example.com/task, http://example.com/employee) and the following two classes:
class Employee(object):
def __init__(self, **kwargs):
self.ID = kwargs['ID']
self.first_name = kwargs['first_name'] if 'first_name' in kwargs else None
self.last_name = kwargs['last_name'] if 'last_name' in kwargs else None
class Task(object):
def __init__(self, **kwargs):
self.ID = kwargs['ID']
self.start_date = kwargs['start_date']
self.employee = Employee(ID=kwargs['employee_id'])
I now want to create Python objects from the json returned by the REST API.
Say that a GET to http://example.com/task/19 returns the following json:
json_data = {'ID': '19', 'start_date': '2018-04-23', 'employee_id': 'xyz1223'}
task = Task(**json_data)
Now, the following all work
print(task.ID) # 19
print(task.start_date) # 2018-04-23
print(task.employee.ID) # xyz1223
but print(task.employee.first_name) returns None. What I would like to happen is that under the hood a GET request to http://example.com/employee/xyz1223 is sent, that the resulting json is parsed, and that the attributes first_name and last_name are filled in.
What is the most pythonic way of doing this?
kwargs['first_name'] if 'first_name' in kwargs else Nonecould bekwargs.get('first_name')