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

Piyush Jiwane
  • 179
  • 3
  • 13

2 Answers2

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
Piyush Jiwane
  • 179
  • 3
  • 13
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
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62