99from app .posts .models import Post , PostSchema
1010from app .api .database import DB
1111
12- API = Namespace ('Posts' ,description = "Post's REST API" )
12+ API = Namespace ('Posts' , description = "Post's REST API" )
1313
1414POSTS_SCHEMA = PostSchema ()
1515
1616POST_FIELDS = API .model ('Post' , {
1717 'name' : fields .String ,
18+ 'title' : fields .String ,
19+ 'body' : fields .String ,
1820 'author_id' : fields .Integer ,
1921})
2022
21- @API .route ('/posts' )
23+
24+ @API .route ('' )
2225class Posts (Resource ):
2326 parser = reqparse .RequestParser ()
24- parser .add_argument ('name' , required = True , type = str , help = "post's name" , location = 'json' )
25- parser .add_argument ('author_id' , required = True , type = int , help = "post's author" , location = 'json' )
27+ parser .add_argument ('name' , required = True , type = str ,
28+ help = "post's name" , location = 'json' )
29+ parser .add_argument ('title' , required = True , type = str ,
30+ help = "post's title" , location = 'json' )
31+ parser .add_argument ('body' , required = True , type = str ,
32+ help = "post's body" , location = 'json' )
33+ parser .add_argument ('author_id' , required = True , type = int ,
34+ help = "post's author" , location = 'json' )
35+
36+ def get (self ):
37+ try :
38+ posts_query = Post .query .all ()
39+ body = jsonify (POSTS_SCHEMA .dump (posts_query , many = True ).data )
40+ if posts_query :
41+ code = HTTPStatus .OK
42+ else :
43+ code = HTTPStatus .NOT_FOUND
44+ except SQLAlchemyError as err :
45+ message = str (err )
46+ body = jsonify ({"message" : message })
47+ code = HTTPStatus .INTERNAL_SERVER_ERROR
48+ return make_response (body , code .value )
2649
2750 @API .expect (POST_FIELDS )
2851 def post (self ):
2952 args_ = self .parser .parse_args ()
30- post = Post (name = args_ ['name' ], author_id = args_ ['author_id' ])
53+ post = Post (name = args_ ['name' ], title = args_ ['title' ], body = args_ [
54+ 'body' ], author_id = args_ ['author_id' ])
3155 try :
3256 DB .session .add (post )
3357 DB .session .commit ()
@@ -40,12 +64,14 @@ def post(self):
4064 code = HTTPStatus .INTERNAL_SERVER_ERROR
4165 return make_response (body , code .value )
4266
43- @API .route ('/post/<int:seqno>' )
67+
68+ @API .route ('/<int:seqno>' )
4469class PostItem (Resource ):
4570 def get (self , seqno ):
4671 try :
47- post_item = DB .session .query (Post ).outerjoin (Users , Users .id == Post .author_id ).filter (Post .id == seqno ).first ()
48- body = jsonify ({"post" :POSTS_SCHEMA .dump (post_item ).data })
72+ post_item = DB .session .query (Post ).outerjoin (
73+ Users , Users .id == Post .author_id ).filter (Post .id == seqno ).first ()
74+ body = jsonify ({"post" : POSTS_SCHEMA .dump (post_item ).data })
4975 if post_item :
5076 code = HTTPStatus .OK
5177 else :
0 commit comments