I need to do a python script to
- Read a csv file with the columns (
person_id
,name
,flag
). The file has 3000 rows. - Based on the
person_id
from the csv file, I need to call a URL passing theperson_id
to do a GET http://api.myendpoint.intranet/get-data/1234 The URL will return some information of theperson_id
, like example below. I need to get all rents objects and save on my csv. My output needs to be like this
import pandas as pd
import requests
ids = pd.read_csv(f"{path}/data.csv", delimiter=';')
person_rents = df = pd.DataFrame([], columns=list('person_id','carId','price','rentStatus'))
for id in ids:
response = request.get(f'endpoint/{id["person_id"]}')
json = response.json()
person_rents.append( [person_id, rent['carId'], rent['price'], rent['rentStatus'] ] )
pd.read_csv(f"{path}/data.csv", delimiter=';' )
person_id;name;flag;cardId;price;rentStatus
1000;Joseph;1;6638;1000;active
1000;Joseph;1;5566;2000;active
Response example
{
"active": false,
"ctodx": false,
"rents": [{
"carId": 6638,
"price": 1000,
"rentStatus": "active"
}, {
"carId": 5566,
"price": 2000,
"rentStatus": "active"
}
],
"responseCode": "OK",
"status": [{
"request": 345,
"requestStatus": "F"
}, {
"requestId": 678,
"requestStatus": "P"
}
],
"transaction": false
}
- After save the additional data from response on csv, i need to get data from another endpoint using the carId on the URL. The mileage result must be save in the same csv. http://api.myendpoint.intranet/get-mileage/6638 http://api.myendpoint.intranet/get-mileage/5566
The return for each call will be like this
{"mileage":1000.0000}
{"mileage":550.0000}
The final output must be
person_id;name;flag;cardId;price;rentStatus;mileage
1000;Joseph;1;6638;1000;active;1000.0000
1000;Joseph;1;5566;2000;active;550.0000
SOmeone can help me with this script? Could be with pandas or any python 3 lib.
Code Explanation
df
, withpd.read_csv
.'person_id'
, are unique..apply
on'person_id'
, to callprepare_data
.prepare_data
expects'person_id'
to be astr
orint
, as indicated by the type annotation,Union[int, str]
API
, which will return adict
, to theprepare_data
function.'rents'
key, of thedict
, into a dataframe, withpd.json_normalize
..apply
on'carId'
, to call theAPI
, and extract the'mileage'
, which is added to dataframedata
, as a column.'person_id'
todata
, which can be used to mergedf
withs
.pd.Series
,s
to a dataframe, withpd.concat
, and thenmerge
df
ands
, onperson_id
.pd.to_csv
in the desired form.Potential Issues
call_api
function.call_api
returns adict
, like the response shown in the question, the remainder of the code will work correctly to produce the desired output.TraceBack
, as text, into a code block.Example