Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert data into sqlite3 database with API

I'm trying to insert data from a web API into my database (I am using sqlite3 on python 3.7.2) and I can't find any tutorials on how do to so. So far all my code is:

import requests, sqlite3
database = sqlite3.connect("ProjectDatabase.db")
cur = database.cursor()

d = requests.get("http://ergast.com/api/f1/2019/drivers")

I'm aiming to get the names and driver numbers of each driver and insert them all into a table called Drivers. (I'm also using more APIs with more tables, but if I figure out how to do one then the rest should be fine.) I assume I have to do something like

cur.execute('''INSERT INTO Drivers VALUES(?,?), (driverName, driverNumber)
''')

but I'm struggling to figure out how to insert the data straight into the table from the website. Does anyone know how to do this? Thanks

like image 277
NotEvenTheRain Avatar asked Oct 15 '25 03:10

NotEvenTheRain


1 Answers

As stated in the comment section in the OP, the problem seemed to be how to parse the API point.

d = requests.get("http://ergast.com/api/f1/2019/drivers.json")
d = d.json()
drivers = d["MRData"]["DriverTable"]["Drivers"]

would be the answer to that question to access all drivers provided by that API.

To add the entries to the db you can use the following:

for dr in drivers:
    name = dr["familyName"]
    number = dr["permanentNumber"]
    sql = 'INSERT INTO Drivers (name,number) VALUES(?,?)'
    val = (name,number)
    cur.execute(sql,val)

with this solution you don't have to use specify the index and can directly access the parameter you're interested in.

like image 139
Vulpex Avatar answered Oct 17 '25 19:10

Vulpex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!