0

I'm trying to create a product API but I am facing this issue after sending a request to the API:

new_product = models.products(name=requests.name, price=requests.price)
AttributeError: module 'fastapi.requests' has no attribute 'name'

This is my code:

main.py

from fastapi import FastAPI, Depends, requests
from typing import Optional
import schemas, models
from database import engine, SessionLocal
from sqlalchemy.orm import Session

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.post('/product')
def create(product: schemas.Products, db : Session = Depends(get_db)):
    new_product = models.products(name=requests.name, price=requests.price)
    db.add(new_product)
    db.commit()
    db.refresh(new_product)
    return new_product

models.py

from sqlalchemy import Column, Integer, String
from database import Base

class products(Base):
    __tablename__ = 'products'
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    price = Column(Integer)    

database.py

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

SQL_URL = 'sqlite:/// product.db'

engine = create_engine(SQL_URL, connect_args={"check_same_thread": False})

SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)

Base = declarative_base()

schemas.py

from pydantic import BaseModel

class Products(BaseModel):
    name: str
    price: int

2 Answers 2

1

If you're trying to get the data sent to the API endpoint, you should be using product.name and product.price, instead of requests.XXX.

You are importing requests from FastAPI (from fastapi import ... requests), and that is completely unrelated to your API!

Sign up to request clarification or add additional context in comments.

Comments

1

Like Jason say is better get info from schema but if you want all the request include the body, headers ... etc you need Request no requests

from fastapi import  Request
@app.post("/")
async def fast_service(request: Request):
    body =await request.body()

    return 

Comments

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.