1

I am new to the FastAPI world, I am creating an API to fetch and post the data to the MySQL database. I followed few link on internet and developed below code

DatabaseConnection.py

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

sql_database_url="mysql://root:root@localhost:3306/first_db"

engine=create_engine(sql_database_url)

sessionLocal=sessionmaker(autocommit=False,bind=engine)

base=declarative_base()

MainClass.py

from fastapi import FastAPI,Query,Depends
from sqlalchemy import Column,String,Integer
from typing import Optional,List
from pydantic import BaseModel
from sqlalchemy.orm import Session

from DatabaseConnection import engine,sessionLocal,base

app=FastAPI()

class User(base):
    __tablename__="users"
    id=Column(Integer,primary_key=True,index=True)
    name=Column(String(255),unique=True,index=True)

class UserSchema(BaseModel):
    id:int
    name:str

    class Config:
        orm_model=True


base.metadata.create_all(bind=engine)

@app.post("/create-user")
def createUser(userSchema:UserSchema):
    user=User(id=userSchema.id,name=userSchema.name)
    sessionLocal().add(user)
    sessionLocal().commit()
    return user

When i try to run this API using UVICorn i was running successful and the table also created successfully but the data that i am sending through the body is not added in the table.
The table is showing null value is added \

I have referred link

Any help will be appreciated. Thanks in advance

2 Answers 2

1

Thanks @anjaneyulubatta505 for help
but we need to do below changes to post data in database

@app.post("/create-user")
def createUser(userSchema:UserSchema):
    user = User(id=userSchema.id, name=userSchema.name)
    with Session(bind=engine) as session:
        session.add(user)
        session.commit()
    return user

referred links

  1. Link1
  2. Link2 from sqlAlChemy
Sign up to request clarification or add additional context in comments.

Comments

0

You are not committing the change to the database. Just change your code like below to make it work.

# ... imports and other stuff
from DatabaseConnection import sessionLocal

@app.post("/create-user")
def createUser(userSchema:UserSchema):
    user = User(id=userSchema.id, name=userSchema.name)
    with sessionLocal() as session:
        session.add(user)
        session.commit()

    return user

5 Comments

Thanks for respond, but with the above code I am getting 500:Internal Server Error
It giving me sqlalchemy.exc.UnboundExecutionError: Could not locate a bind configured on mapper mapped class User->users, SQL expression or this Session. error msg
@PiyushJiwane updated the code. you can check it now. make sure you imoprt localSession correctly.
Hi, still getting same error
I found a solution and we need to do below changes with Session(bind=engine) as session:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.