everyone! So basically I have this problem. I'm trying to make a request to a zipcode API on Brazil, but the data is showed on the JSON format. What I have to do, it's to take this information from the API and put it on a SQLlite database. But, somehow I don't know how to do it. I tried to use this code:
import requests
import sqlite3
import json
print('Identifying the ZIP CODE')
CEPC = input('Please type the zipcode:')
Requisicao = requests.get('https://viacep.com.br/ws/%7B%7D/json/%27.format(CEPC))
print(Requisicao.json())
#Database
con = sqlite3.connect('CEPS.db')
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS Requisicao')
cur.execute("CREATE TABLE Requisicao (cep int(8), data json)")
for Requisicao1 in Requisicao:
cur.execute("insert into Requisicao values (8, 5)",
[Requisicao1['cep'], json.dumps(Requisicao1)])
cur.commit()
cur.close()
It's all working when I try to make the request to the API, but when I try to insert the data on the database I just can't. When it come to this code part:
for or Requisicao1 in Requisicao:
cur.execute("insert into Requisicao values (8, 5)",
[Requisicao1['cep'], json.dumps(Requisicao1)])
It gives me the error: TypeError: byte indices must be integers or slices, not str.
Examples of zipcodes are: 09931080, 05565000.
The outpout to the zipcode example is:
{
"cep": "05565-000",
"logradouro": "Avenida General Asdrúbal da Cunha",
"complemento": "",
"bairro": "Jardim Arpoador",
"localidade": "São Paulo",
"uf": "SP",
"ibge": "3550308",
"gia": "1004",
"ddd": "11",
"siafi": "7107"
}
This is the output when I try to get the request.