question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 6 - probably unsupported type

See original GitHub issue

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Hello everyone, I’ve been learning fastapi since Sunday and have read the documentation a bit and wanted to apply it to a small example, but I get the following error message, I ask for help to fix it. The other issues didn’t help me. Thank you!

from typing import List

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session

from . import crud, models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI(debug=True)


#Dependency 
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@app.post("/exercises/", response_model=schemas.Exercise)
def create_exercise(exercise: schemas.ExerciseCreate, db: Session = Depends(get_db)):
    """
    Create a exercise instance and store it in to the database.
    """
    return crud.create_exercise(db=db, exercise=exercise)


@app.get("/exercises/", response_model=List[schemas.Exercise])
def read_exercises(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """
    Retrieve max 100 exercises objects from the database.
    """
    exercises = crud.get_exercises(db, skip=skip, limit=limit)
    return exercises


@app.get("/exercises/{exercise_id}", response_model=schemas.Exercise)
def read_exercise(exercise_id: int, db: Session = Depends(get_db)):
    """
    Retrieve a specific exercise from the database.
    """
    exercise = crud.get_exercise_by_id(db, exercise_id=exercise_id)
    if exercise is None:
        raise HTTPException(status_code=404, detail="Exercise not found")
    return exercise

from typing import Optional, List, Set
from pydantic import BaseModel


class ExerciseBase(BaseModel):
    """
    Class for parshing a exercise object while creating or reading data.
    """
    name: str
    picture: Optional[str] = None
    description: str
    tip: Optional[str] = None
    variations: Optional[str] = None
    equipment: Optional[str] = None
    tags: Optional[Set[str]] = None
    subtags: Optional[Set[str]] = None
    sporttype: str
    online: bool


class ExerciseCreate(ExerciseBase):
    """
    Class for creating a exercise object.
    """
    pass


class Exercise(ExerciseBase):
    """
    Class for reading exercises from the API.
    """
    id: int
    name: str
    description: str
    sporttype: str
    online: bool
    

    class Config:
        orm_mode = True


from sqlalchemy import Boolean, Integer, Column, String
from .database import Base


class Exercise(Base):
    __tablename__ = "exercises"

    id = Column("exercise_id", Integer, primary_key=True, index=True)
    name = Column(String, unique=True, index=True)
    picture = Column(String)
    description = Column(String)
    tip = Column(String)
    variations = Column(String)
    equipment = Column(String)
    tags = Column(String)
    subtags = Column(String)
    sporttype = Column(String)
    online = Column(Boolean)

from sqlalchemy.orm import Session
from . import models, schemas


def get_exercise_by_id(db: Session, exercise_id: int):
    """
    Read a exercise by id from the database.

    Paramerters
    -----------
    db: Session(instance of the databse for type hints)
    exercise_id: int
    """
    return db.query(models.Exercise).filter(models.Exercise.id == exercise_id).first()


def get_exercises(db: Session, skip: int = 0, limit: int = 100):
    """
    Retrieve maxi 100 exercises from the database.

    Paramerters
    -----------
    db: Session(instance of the databse)
    skip: int
    limit: int
    """
    return db.query(models.Exercise).offset(skip).limit(limit).all()


def create_exercise(db: Session, exercise: schemas.ExerciseCreate):
    """
    Create a exercise instance and store it in to the database.
    
    Parameters
    ----------
    db: Session(instance of the database)
    exercise: Exercise
    
    return
    -------
    exercise instance
    """
    ex_obj = models.Exercise(**exercise.dict())
    db.add(ex_obj)
    db.commit()
    db.refresh(ex_obj)
    return ex_obj

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./exercise.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
    )
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

Debuger mode

File "c:\exercise\venv\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "c:\exercise\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__
    raise exc from None
  File "c:\exercise\venv\lib\site-packages\starlette\exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "c:\exercise\venv\lib\site-packages\starlette\routing.py", line 566, in __call__
    await route.handle(scope, receive, send)
  File "c:\exercise\venv\lib\site-packages\starlette\routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "c:\exercise\venv\lib\site-packages\starlette\routing.py", line 41, in app
    response = await func(request)
  File "c:\exercise\venv\lib\site-packages\fastapi\routing.py", line 182, in app
    raw_response = await run_endpoint_function(
  File "c:\exercise\venv\lib\site-packages\fastapi\routing.py", line 135, in run_endpoint_function
    return await run_in_threadpool(dependant.call, **values)
  File "c:\exercise\venv\lib\site-packages\starlette\concurrency.py", line 34, in run_in_threadpool
    return await loop.run_in_executor(None, func, *args)
  File "C:\Users\MATHIASKOLIE\AppData\Local\Programs\Python\Python38\lib\concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File ".\app\main.py", line 28, in create_exercise
    return crud.create_exercise(db=db, exercise=exercise)
  File ".\app\crud.py", line 45, in create_exercise
    db.commit()
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1042, in commit
    self.transaction.commit()
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\session.py", line 504, in commit
    self._prepare_impl()
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\session.py", line 483, in _prepare_impl
    self.session.flush()
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2536, in flush
    self._flush(objects)
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2678, in _flush
    transaction.rollback(_capture_exception=True)
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
    compat.raise_(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise_
    raise exception
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\session.py", line 2638, in _flush
    flush_context.execute()
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 422, in execute
    rec.execute(self)
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 586, in execute
    persistence.save_obj(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 239, in save_obj
    _emit_insert_statements(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1135, in _emit_insert_statements
    result = cached_connections[connection].execute(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1011, in execute
    return meth(self, multiparams, params)
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 298, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1124, in _execute_clauseelement
    ret = self._execute_context(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1316, in _execute_context
    self._handle_dbapi_exception(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1510, in _handle_dbapi_exception
    util.raise_(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\util\compat.py", line 182, in raise_
    raise exception
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1276, in _execute_context
    self.dialect.do_execute(
  File "c:\exercise\venv\lib\site-packages\sqlalchemy\engine\default.py", line 593, in do_execute
    cursor.execute(statement, parameters)

Response headers

Command line error message

cursor.execute(statement, parameters)
sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 6 - probably unsupported type.
[SQL: INSERT INTO exercises (name, picture, description, tip, variations, equipment, tags, subtags, sporttype, online) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: ('Climb', 'string', 'Im Stand', 'string', 'string', 'string', {'string'}, {'string'}, 'Fitness', 1)]

Environment

  • OS: [e.g. Linux / Windows / macOS]: Windows

  • FastAPI Version [e.g. 0.3.0]: 0.61.2

  • Python version: 3.8.1

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Mausecommented, Nov 25, 2020

Very few databases have a set type, and sqlite, the one you’re using, doesn’t

0reactions
parasdalsaniyacommented, Oct 13, 2021

`from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from sqlalchemy.exc import SQLAlchemyError from flask_marshmallow import Marshmallow from flask_cors import CORS

from datetime import date, datetime

import os

from marshmallow.fields import Date

init app

app = Flask(name)

CORS(app)

basedir = os.path.abspath(os.path.dirname(file))

database

app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘sqlite:///’ + os.path.join(basedir, ‘db.sqlite’) app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS’] = False

Init db

db = SQLAlchemy(app)

Init ma

ma = Marshmallow(app)

Book Class/Model

class Book(db.Model): bid = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(300)) authors = db.Column(db.String(300)) average_rating = db.Column(db.Integer()) language_code = db.Column(db.String(10)) num_pages = db.Column(db.Integer()) ratings_count = db.Column(db.Integer()) text_reviews_count = db.Column(db.Integer()) # publication_date = db.Column(db.DateTime() ) publisher = db.Column(db.String(100)) isbn = db.Column(db.String(300)) isbn13 = db.Column(db.String(300)) stock = db.Column(db.Integer(), default=1) price = db.Column(db.Integer(), default=100) # revenue = db.Column(db.Integer(), default=0, nullable=False) # transactions = db.relationship(“Transaction”, backref=“book”, lazy=True) print(title, authors, average_rating, language_code, num_pages, ratings_count, text_reviews_count, publisher, isbn, isbn13, stock, price)

def __init__(self, title, authors, average_rating, language_code, num_pages, ratings_count, text_reviews_count, publisher, isbn, isbn13, stock, price):
    self.title= title,
    self.authors = authors, 
    self.average_rating= average_rating,
    self.language_code= language_code,
    self.num_pages= num_pages,
    self.ratings_count= ratings_count,
    self.text_reviews_count= text_reviews_count,
    # self.publication_date= publication_date,
    self.publisher= publisher,
    self.isbn= isbn,
    self.isbn13= isbn13,
    self.stock= stock,
    self.price= price,

book class

class BookSchema(ma.Schema): class Meta: fields = (‘bid’, ‘title’, ‘authors’, ‘average_rating’, ‘language_code’, ‘num_pages’, ‘ratings_count’, ‘text_reviews_count’, ‘publisher’, ‘isbn’, ‘isbn13’, ‘stock’, ‘price’)

init schema

book_schema = BookSchema() books_schema = BookSchema(many=True)

add book

@app.route(‘/book’, methods=[‘POST’]) def add_book(): title= request.json[‘title’], authors = request.json[‘authors’], average_rating= request.json[‘average_rating’], language_code= request.json[‘language_code’], num_pages= request.json[‘num_pages’], ratings_count= request.json[‘ratings_count’], text_reviews_count= request.json[‘text_reviews_count’], # publication_date= datetime(2015, 6, 5, 8, 10, 10, 10),date.today().strftime(“%Y-%m-%d”),request.json[‘publication_date’], publisher= request.json[‘publisher’], isbn= request.json[‘isbn’], isbn13= request.json[‘isbn13’], stock= request.json[‘stock’], price= request.json[‘price’], # print(title, authors, average_rating, language_code, num_pages, ratings_count, text_reviews_count, publisher, isbn, isbn13, stock, price)

new_book = Book(title, authors, average_rating, language_code, num_pages, ratings_count, text_reviews_count, publisher, isbn, isbn13, stock, price)
try:
    db.session.add(new_book)
    print("add done",new_book)
    db.session.commit()
    print("comit done")
except SQLAlchemyError as e:
    error = str(e.__dict__['orig'])
    print("notdone")

    return error
# except:
#     print("notdone")

return book_schema.jsonify(new_book)

get all book

@app.route(‘/book’, methods=[‘GET’]) def get_books(): all_books = Book.query.all() result = books_schema.dump(all_books) return jsonify(result)

get one book

@app.route(‘/book/<bid>’, methods=[‘GET’]) def get_book(id): book = Book.query.get(id) return book_schema.jsonify(book)

update a book

@app.route(‘/book/<bid>’, methods=[‘PUT’]) def update_book(id): book = Book.query.get(id)

book.title= request.json['title'],
book.authors = request.json['authors'],
book.average_rating= request.json['average_rating'],
book.language_code= request.json['language_code'],
book.num_pages= request.json['num_pages'],
book.ratings_count= request.json['ratings_count'],
book.text_reviews_count= request.json['text_reviews_count'],
# book.publication_date= datetime(2015, 6, 5, 8, 10, 10, 10),
book.publisher= request.json['publisher'],
book.isbn= request.json['isbn'],
book.isbn13= request.json['isbn13'],
book.stock= request.json['stock'],
book.price= request.json['price'],

db.session.commit()

return book_schema.jsonify(book)

delete prbook

@app.route(‘/book/<bid>’, methods=[‘DELETE’]) def delete_book(id): book = Book.query.get(id) db.session.delete(book) db.session.commit()

return book_schema.jsonify(book)

run server

if name == ‘main’: app.run(debug=True) ` I have same issue but I can’t solve this. please help me

Read more comments on GitHub >

github_iconTop Results From Across the Web

sqlite3.InterfaceError: Error binding parameter 1 - probably ...
Error binding parameter 1 - probably unsupported type. is reporting that the value at position 1 * in the sequence of values passed...
Read more >
sqlite3.InterfaceError: Error binding parameter 0 - probably ...
InterfaceError : Error binding parameter 0 - probably unsupported type. Best I can tell from reddit API is that all data returned is...
Read more >
Getting this error Error sqlite3 InterfaceError Error binding ...
I am using python 2.7 with pyqt4.10 and sqlite3 Db, trying to get the user input ... : Error binding parameter 0 -...
Read more >
(sqlite3.InterfaceError) Error binding parameter 0 - probably ...
Discussion: [sqlalchemy] sqlalchemy.exc.InterfaceError: (sqlite3.InterfaceError) Error binding parameter 0 - probably unsupported type. [SQL: 'UPDATE ruleresult ...
Read more >
sqlite3.InterfaceError: Error binding parameter 0 - Python Forum
This error is a DBAPI Error and originates from the database driver (DBAPI), not SQLAlchemy itself. The InterfaceError is sometimes raised by ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found