Search code examples
python-3.xsqlalchemyfastapi

SqlAlchemy and FastApi


I am new to SqlAlchemy and FastApi. I am working on an example that does not show the expected output.

I get an error in Swagger

from fastapi import FastAPI, Body, Depends
import uvicorn
from typing import List
from pydantic import BaseModel, Field, constr


from sqlalchemy import create_engine
from sqlalchemy.dialects.sqlite import *
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args = {"check_same_thread": False})
session = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

class Books(Base):
   __tablename__ = 'book'
   id = Column(Integer, primary_key=True, nullable=False)
   title = Column(String(50), unique=True)
   author = Column(String(50))
   publisher = Column(String(50))
   Base.metadata.create_all(bind=engine)



class Book(BaseModel):
   id: int
   title: str
   author:str
   publisher: str
   class Config:
      orm_mode = True


app=FastAPI()
def get_db():
   db = session()
   try:
      yield db
   finally:
      db.close()

@app.post('/add_new', response_model=Book)

def add_book(b1: Book, db: Session = Depends(get_db)):
   bk=Books(id=b1.id, title=b1.title, author=b1.author, publisher=b1.publisher)
   db.add(bk)
   db.commit()
   db.refresh(bk)
   return Books(**b1.dict())

The error is Internal Server Error. Many people got the same error and they refer to SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" to fix it. I don't really know what to do.

Can someone help please. Thanks


Solution

  • There is metadata for creating table, now you try to access table but it doesn't exist so first creat it. Like this Base.metadata.create_all(bind=engine)