How to join data from two API in Python
So, far I have only used get/post data from one API at a time. I am not sure how can I join data from two API. Similar like SQL, is there a some sort of Join tables to achieve same with the API?
I would like to display staff photos with other staff details in html template.
API 1
https://test.com/api/Staff/GetStaffDetails
StaffId, Firstname, Lastname, Email
API 2
https://test.com/api/Staff/GetStaffPhotos
Id (this matches with the StaffId), Photo
Staff Details
def StaffDetails(request, *, context):
url = "https://test.com/api/Staff/GetStaffDetails"
headers = {
"X-DOMAIN": "test",
"X-TOKEN": "123456789qwertyuiop",
"User-Agent": "",
}
response = requests.post(url, headers=headers)
data = response.json()
random_data = random.sample(data, min(5, len(data)))
context = {"data": random_data}
return render(request, "StaffDetails.html", context)
StaffDetails.html
<table border="1">
<tr>
<td>STAFFID</td>
<td>FIRSTNAME</td>
<td>LASTNAME</td>
<td>EMAIL</td>
</tr>
{% for row in data %}
<tr>
<td>{{ row.StaffId }}</td>
<td>{{ row.Firstname }}</td>
<td>{{ row.Lastname }}</td>
<td>{{ row.Email }}</td>
</tr>
{% endfor %}
</table>
Staff Photo
def StaffPhoto(request, *, context):
url = "https://test.com/api/Staff/GetStaffPhotos"
headers = {
"X-DOMAIN": "test",
"X-TOKEN": "123456789qwertyuiop",
"User-Agent": "",
}
response = requests.post(url, headers=headers)
data = response.json()
random_data = random.sample(data, min(5, len(data)))
context = {"data": random_data}
return render(request, "StaffPhoto.html", context)
StaffPhoto.html
<table border="1">
<tr>
<td>ID</td>
<td>PHOTO</td>
</tr>
{% for row in data %}
<tr>
<td>{{ row.Id }}</td>
<td><img src="data:image/jpeg;base64,{{ row.Photo }}" width="100px"></td>
</tr>
{% endfor %}
</table>
Thank you.
It seems you have images as list of dictionares
[{'id': number1, 'image': image1}, {'id': number2, 'image': image2}, ...]
but if you convert it to dictionary
{number1:image1, number2:image2}
then you don't need to join it. because you can directly use row['StaffId']
to get image from this dictionary
Minimal working example:
data_staff = [
{'StaffId': 1, 'Firstname': 'A', 'Lastname':'A', 'Email': 'A.A@gmail.com'},
{'StaffId': 2, 'Firstname': 'B', 'Lastname':'B', 'Email': 'B.B@gmail.com'},
{'StaffId': 3, 'Firstname': 'C', 'Lastname':'C', 'Email': 'C.C@gmail.com'},
{'StaffId': 4, 'Firstname': 'D', 'Lastname':'D', 'Email': 'D.D@gmail.com'},
]
data_images = [
{'id': 1, 'image': 'image_A_A'},
{'id': 2, 'image': 'image_B_B'},
{'id': 3, 'image': 'image_C_C'},
{'id': 4, 'image': 'image_D_D'},
]
# convert to dictionary
images = {item['id']:item['image'] for item in data_images}
for item in data_staff:
_id = item['StaffId']
print(_id, item['Firstname'], images[_id])
Result:
1 A image_A_A
2 B image_B_B
3 C image_C_C
4 D image_D_D