Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
FastAPI Python Database connectivity

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

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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
over 4 years ago · Santiago Trujillo Denunciar

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
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda