Changing response Status Codes
Lets set up the code required for a NULL return
If we use the
ID = 5
via Postman we will get a NULL Response since there is noID = 5
stored
There are multiple HTTP Codes that are being used but since there is no ID in the database for our request, we require in this case a
HTTP 404
MessageFirst we need to import
Response
fromFastAPI
Now we can modify our code to accept responses
We have set it up so that if no post is found, it will return 404, so the return of the HTTP request still might be NULL but the response code is 404
There is a better way of doing things
Same concept but just a better overall implementation method
We need to import
status
fromFastAPI
Now we can simply say
status.
and this will return all HTTP Statuses
Additionally returning a NULL response looks ugly so we're going to add a code line to return a 404 message
This will return only if the post is not found
This returns HTTP code 404 with message:
The above method is fine but a little sloppy, there is a even better way of raising this sort of exceptions so that you don't have to hardcode values
We will import
HTTPException
fromFastAPI
Then we will use the
HTTPException
to pass both HTTP code and the return message
The code cleaned up:
This way you have both on a single line of code
Returning a HTTP code inside the decorator
Based on the HTTP Documentation, we should return a HTTP 201 every time there is a new post created
To do this we need to provide the decorator with an additional variable for this
Now that we have passed the
status_code
variable in the decorator the HTTP Request returns 201
Last updated