1

hello i have the following function in fastapi python

    from fastapi.encoders import jsonable_encoder
    from fastapi.responses import JSONResponse
    from fastapi import Response
    import json
    import pyodbc
    import pandas as pd
    from fastapi import FastAPI
    from typing  import Optional
    from typing import Union

@app.get("/periodikes/sql_2")
def results_to_json():
    conn = pyodbc.connect('blah blah')
    cursor = conn.cursor()
    query_result = "select top 100 * from table"
    cursor.execute(query_result)
    datashet = cursor.fetchall()
    print(cursor.description)
    cursor.close()
    conn.close()
    json_compatible_item_data = jsonable_encoder(datashet)
    return JSONResponse(content=json_compatible_item_data)

this get method results in ValueError: [ValueError('dictionary update sequence element #0 has length 32; 2 is required'), TypeError('vars() argument must have dict attribute')] what can i do to return the results of query as json with the name of the column and the value like this

{
    "crmIFE_ReturnCode": "203",
    "crmIFE_ActionID": "0F09630A1C754B408CAF3C0B47CD4577",
    "crmBA_ID": "0F09630A1C754B408CAF3C0B47CD4577",
 }
asdaswsad
  • 17
  • 2
  • please provide the full stacktrace, somewhere you're feeding the wrong data type to a function that expects a dictionary and seems to be receiving a list instead. – Hedde van der Heide Dec 07 '22 at 11:47
  • There is also no reason to manually convert anything to JSON, FastAPI will handle that automagically for you. You can apply a pydantic model as the `response_model` to your `@app.get` decorator as well to filter (and validate) the fields returned from your api from the database. – MatsLindh Dec 07 '22 at 14:03

0 Answers0