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