In this guide, we’ll enhance our CRUD application by introducing the functionality to retrieve a single post using its ID. Previously, we implemented features to create a new post and to retrieve all posts. Now, we’ll add a function that returns one specific post based on an ID provided as a path parameter in the URL. Below is the code snippet for creating a post. When a new post is created, it is assigned a random ID before being appended to our list of posts.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Retrieving an Individual Post
We’ll implement a function calledget_post for retrieving a single post. The endpoint will have the following structure: /posts/{id}, where {id} is a path parameter representing the post’s ID requested by the user. FastAPI automatically extracts this parameter and makes it available to the function.
Initially, you might define the endpoint like this:
/posts/1, FastAPI extracts the value 1 as a string and passes it to the function. Such a parameter embedded in the URL is known as a path parameter.
Using a Helper Function to Locate a Post
Our application stores posts in a list calledmy_posts. To find a post by its specific ID, we can define a helper function, find_post, which iterates through the list and returns the matching post:
get_post function to utilize the find_post helper function and return the located post:
Handling Type Conversions
Keep in mind that path parameters are received as strings by default. For instance, when the URL/posts/2 is accessed, the id inside the function will be the string "2", not the integer 2. This mismatch could cause the equality check to fail when comparing with integers stored in my_posts.
To address this, convert the id to an integer before using it in find_post:
If a non-numeric value is passed (e.g.,
/posts/asdfasdf), converting the string to an integer will raise a ValueError and result in an internal server error.Leveraging FastAPI’s Validation
FastAPI simplifies parameter types by validating and converting them automatically. By declaring theid parameter as an int in the function signature, FastAPI converts the parameter before the function is executed. If the conversion fails, FastAPI provides a clear and informative error message.
Update the function signature accordingly:
id, FastAPI responds with a validation error similar to the following:
Final Function Example
Below is the complete version of our individual post retrieval implementation, including the helper function and the supporting code:This implementation not only provides robust type validation for the path parameter but also lays the groundwork for future extensions like updating or deleting posts. Explore additional documentation in the FastAPI official docs for further enhancements.