Python Forum
Read JSON via API and write to SQL database
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read JSON via API and write to SQL database
#1
Hello everyone, I'm new to Python and new to the forum.

I'm developing a Python program that accesses an API, this API returns a JSON and this return I have to write to a SQL database.

API access is OK, the problem is writing to the bank.

Here's the source code I'm using.

from optparse import Values
from turtle import st
from urllib import request
import requests
import pyodbc
import json
import textwrap

request = requests.get('http://SRVAPI:8280/api/cdp/v1/getCliente')

addressData = request.json()
jsonString = json.dumps(addressData['items'])

server = 'SRVBanco' 
dataBase = 'DWSimu' 
userName = 'sa' 
passWord = 'senha'

conexao = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+dataBase+';UID='+userName+';PWD='+ passWord)

cursor = conexao.cursor()
valoresInserir = []

for cliente in jsonString:
    clienteId = cliente['clienteId']
    nomeAbrev = cliente['nomeAbrev']
    nome = cliente['nome']

    linhaInserir = (clienteId, nomeAbrev, nome)
    valoresInserir.append(linhaInserir)

comandoSQL = "INSERT INTO cliente (cliente_id, nome_abrev, nome) VALUES (%s, %s, %s)"
cursor.executemany(comandoSQL, valoresInserir)
conexao.commit()

cursor.close()
conexao.close()
Following is the error that is returned.

Traceback (most recent call last):
File "c:\Projetos\api\getCliente.py", line 25, in <module>
clienteId = cliente['clienteId']
TypeError: string indices must be integers

One detail, the customerId field is integer

Translated by Google
Reply
#2
Line 12 is wrong,here you dump to string then can iterate over to get key in line 24.
Use addressData(it's a dictionary) as Requests has build in json decoder(don't need import json).

Try change line 24 to:
for cliente in addressData['items']:
Reply
#3
(Aug-09-2022, 03:12 PM)snippsat Wrote: Line 12 is wrong,here you dump to string then can iterate over to get key in line 24.
Use addressData(it's a dictionary) as Requests has build in json decoder(don't need import json).

Try change line 24 to:
for cliente in addressData['items']:

Hello, I changed as requested, but it gave the following error.

Traceback (most recent call last):
File "c:\Projetos\api\getCliente.py", line 33, in <module>
cursor.executemany(comandoSQL, valoresInserir)
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 3 parameters were supplied', 'HY000')
Reply
#4
Here's a snippet of the JSON

[{"clienteId": 0, "nomeAbrev": "PEF", "nome": "PAGAMENTO EXTRA FORNECEDOR"}]
Reply
#5
Instead of %s use parameters marker (placeholder) ?
TecInfo likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
(Aug-09-2022, 04:31 PM)buran Wrote: Instead of %s use parameters placeholder ?

Perfect!
Thanks a lot for the help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,455 Nov-09-2023, 10:56 AM
Last Post: mg24
Question Special Characters read-write Prisonfeed 1 622 Sep-17-2023, 08:26 PM
Last Post: Gribouillis
  How do I read and write a binary file in Python? blackears 6 6,627 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Pymodbus read and save to database stewietopg 3 1,870 Mar-02-2023, 09:32 AM
Last Post: stewietopg
  Read text file, modify it then write back Pavel_47 5 1,614 Feb-18-2023, 02:49 PM
Last Post: deanhystad
  write json into a table herobpv 4 1,507 Jan-22-2023, 04:36 AM
Last Post: herobpv
  how to read txt file, and write into excel with multiply sheet jacklee26 14 10,016 Jan-21-2023, 06:57 AM
Last Post: jacklee26
  Read nested data from JSON - Getting an error marlonbown 5 1,369 Nov-23-2022, 03:51 PM
Last Post: snippsat
  Write and read back data Aggie64 6 1,885 Apr-18-2022, 03:23 PM
Last Post: bowlofred
Question How do I skipkeys on json file read to python dictionary? BrandonKastning 3 1,897 Mar-08-2022, 09:34 PM
Last Post: BrandonKastning

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020