88from api .db .database import get_db
99from api .v1 .models .blog import Blog
1010from api .v1 .schemas .blog import (
11- BlogCreateResponseSchema ,
1211 BlogCreateSchema ,
1312 BlogListItemResponseSchema ,
1413 BlogListResponseSchema ,
14+ BlogResponseSchema ,
1515)
1616
1717blog = APIRouter (prefix = "/blogs" , tags = ["Blog" ])
2121
2222@blog .post (
2323 "" ,
24- response_model = BlogCreateResponseSchema ,
24+ response_model = BlogResponseSchema ,
2525 status_code = status .HTTP_201_CREATED ,
2626)
2727async def create_blog (
2828 blog : BlogCreateSchema ,
2929 db : Session = Depends (get_db ),
30- ) -> BlogCreateResponseSchema :
30+ ) -> BlogResponseSchema :
3131 try :
3232 existing_blog = db .query (Blog ).filter (Blog .title == blog .title ).first ()
3333 if existing_blog :
@@ -48,7 +48,7 @@ async def create_blog(
4848 db .refresh (new_blog )
4949 logger .info (f"Blog post '{ new_blog .title } ' created successfully." )
5050
51- return BlogCreateResponseSchema .model_validate (new_blog .__dict__ )
51+ return BlogResponseSchema .model_validate (new_blog .__dict__ )
5252
5353 except HTTPException as http_err :
5454 logger .warning (f"HTTP error occurred: { http_err .detail } " )
@@ -127,3 +127,51 @@ async def list_blog(
127127 status_code = status .HTTP_500_INTERNAL_SERVER_ERROR ,
128128 detail = "Internal server error." ,
129129 )
130+
131+
132+ @blog .get (
133+ "/{id}" ,
134+ response_model = BlogResponseSchema ,
135+ status_code = status .HTTP_200_OK ,
136+ )
137+ async def read_blog (
138+ id : int ,
139+ db : Session = Depends (get_db ),
140+ ) -> BlogResponseSchema :
141+ try :
142+ blog = (
143+ db .query (Blog )
144+ .filter (
145+ Blog .id == id ,
146+ not_ (Blog .is_deleted ),
147+ )
148+ .first ()
149+ )
150+ if not blog :
151+ logger .warning (f"Blog post with ID '{ id } ' not found." )
152+ raise HTTPException (
153+ status_code = status .HTTP_404_NOT_FOUND ,
154+ detail = "Blog post not found." ,
155+ )
156+
157+ logger .info (f"Blog post with ID '{ id } ' retrieved successfully." )
158+ return BlogResponseSchema .model_validate (blog .__dict__ )
159+
160+ except SQLAlchemyError as e :
161+ logger .error (f"Database error occurred: { e } " )
162+ raise HTTPException (
163+ status_code = status .HTTP_500_INTERNAL_SERVER_ERROR ,
164+ detail = "Database error occurred." ,
165+ )
166+ except ValueError as e :
167+ logger .error (f"Invalid blog post ID '{ id } ': { e } " )
168+ raise HTTPException (
169+ status_code = status .HTTP_400_BAD_REQUEST ,
170+ detail = "Invalid blog post ID." ,
171+ )
172+ except Exception as e :
173+ logger .error (f"Unexpected error occurred: { e } " )
174+ raise HTTPException (
175+ status_code = status .HTTP_500_INTERNAL_SERVER_ERROR ,
176+ detail = "Unexpected error occurred." ,
177+ )
0 commit comments