Home > other >  FastAPI sqlite Inserting data to a database
FastAPI sqlite Inserting data to a database

Time:10-16

I am new to FastAPI and am playing around to get to know the framework. I am trying to insert data into my database but I am missing something.

Here's my model:

from datetime import datetime
from pydantic import BaseModel

class Article(BaseModel):
    id: int
    title: str
    slug: str
    content: str
    author: str
    date: datetime

class InArticle(BaseModel):
    title: str
    slug: str
    content: str
    author: str

and here's the logic

@app.post("/articles", response_model=InArticle)
async def create_article(article: InArticle):
    cursor = connexion.cursor()
    article_obj = (InArticle(
        title=article.title,
        slug=article.slug,
        content=article.content,
        author=article.author
    ))
    db_query = """INSERT INTO Article (title, slug, content, author) 
                    VALUES (?, ?, ?, ?)"""
    cursor.execute(db_query, article_obj)
    connexion.close()
    return article

I get this error:

cursor.execute(db_query, article_obj)
ValueError: parameters are of unsupported type

What am I missing ?

CodePudding user response:

SQLAlchemy is complaing about you giving it a single article_obj - which it has no idea what to do with. If you plan to issue the queries manually (you might want to look at SQLModel or using SQLAlchemy's ORM), you're going to have to give the parameters separately.

To use the syntax you've given you should either give the values manually:

cursor.execute(db_query, article.title, article.slug, article.content, article.author)

.. or with named parameters instead:

db_query = """INSERT INTO Article (title, slug, content, author) 
                VALUES (:title, :slug, :content, :author)"""

# .. which you can then expand automagically
cursor.execute(db_query, **article_obj.dict())
# **article_obj.dict() expands it to title=article_obj.title, ..etc
  • Related