Object post has no attribute post.title – API attribute error

Question:

Building an API and getting an error that doesn’t make sense. Here is the code:

  from typing import Optional
from fastapi import Body, FastAPI, Response,status
import psycopg2
import time
from pydantic import BaseModel
from psycopg2.extras import RealDictCursor
app = FastAPI()

while True:
    try :
        conn=psycopg2.connect(host='localhost', database='FASTAPIdb' , user= 'postgres' , password= '----', cursor_factory= RealDictCursor)
        cursor=conn.cursor()
        print('Connection to database succesfull')
        break
    except Exception as error:
        print('Connection to database failed')
        print('Error', error)
        time.sleep(2)


class post(BaseModel):
    title: str
    content: str
    published: bool=True
    


@app.get("/")
def root():

    return {"message": "sup biatch"}

@app.get("/posts",status_code=status.HTTP_200_OK)
def get_posts():
    cursor.execute("select * from posts")
    posts=cursor.fetchall()

    return {'data':posts}

@app.get("/post/id", status_code=status.HTTP_200_OK)
def find_posts(id):
    return {'post': 'retrieved post'} 


@app.post("/createpost", status_code= status.HTTP_201_CREATED)
def create_posts(postcreated: post):
    cursor.execute("""insert into posts (title,content,published) VALUES(%s,%s,%s) RETURNING * """,(post.title,post.content,post.published))
    new_post=cursor.fetchone()
    conn.commit()
    return {'new post': "new post returned"}

I am building an API to post some data to a Postgres database and I’m getting a server error: type object post has no attribute title.
As you can see it clearly does. What’s going on?
I’m using postman to test it.

Asked By: C A OB1

||

Answers:

The error says it all post has no attribute title, which is triggered on the line

cursor.execute("""insert into posts (title,content,published) VALUES(%s,%s,%s) RETURNING * """,(post.title,post.content,post.published))

The variable post does not have the field title (and I guess the other two as well).

The problem I can spot in your code is that you’re using the post class instead of the variable holding the post‘s data. You should be therefore use the variable postcreated of type post from line

def create_posts(postcreated: post):

Note about the question

next time publish the exact error you get, which will contain useful information for those who read the question. This case is an exception, since the error can be spotted by reading the code

Answered By: lsabi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.