FastAPI, detail "Method Not Allowed" on post method

  fastapi, python, python-requests, restapi

I am stuck on this problem not able to figure it out, Thank you for guiding me in the right direction.
When I try with the swagger, I am only getting Internal server error while data is been stored in the database,
while trying direct URL I am getting Detail: "Method NOT allow"
I am guessing the problem with the body part of the request. Still unsure

main.py

@app.post("/product", response_model=product.Product)
async def create_product_for_ecom(pro: product.Product, db: Session = Depends(get_db)):
    db_product = crud.get_product_by_name(db, name=pro.product_name)
    if db_product:
        raise HTTPException(status_code=400, detail="product already registered")
    result = crud.create_product(db=db, Cproduct=pro)
    return result


@app.post("/category/", response_model=product.Category)
async def create_category_for_ecom(cat: product.Category, db: Session = Depends(get_db)):
    return crud.create_category_item(db, cat)

Model.py

class Product(Base):
    __tablename__ = "products"
    id = Column(Integer, primary_key=True, index=True)
    p_name = Column(String(25))
    p_price = Column(Float)
    p_dec = Column(String(100))
    category_id = Column(Integer, ForeignKey("categories.id"))
    categoryFK = relationship("Category", back_populates="productFK", uselist=False)


class Category(Base):
    __tablename__ = "categories"
    id = Column(Integer, primary_key=True, default=False)
    category = Column(String(25))
    cat_desc = Column(String(500))
    productFK = relationship("Product", back_populates="categoryFK") #, cascade="all, delete-orphan"


Base.metadata.create_all(bind=engine)

Schema.py

class Product(BaseModel):
    product_name: str 
    product_price: float
    product_description:str
    category_id: int
    
class Category(BaseModel):
    category: str
    category_desc:Optional[str]=None

    class Config:
        orm_mode=True

crud.py

def create_product(db: Session, Cproduct: product.Product):
    db_user = model.Product(p_name=Cproduct.product_name, p_price=Cproduct.product_price,
                            p_dec=Cproduct.product_description, category_id=Cproduct.category_id)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def create_category_item(db: Session, cate: product.Category):
    db_item = model.Category(category=cate.category, cat_desc=cate.category_desc)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item

Source: Python Questions

LEAVE A COMMENT