In this task, you will build the API endpoints for managing posts in the Posts application. You will create routes for reading all posts, reading a specific post by ID, creating a new post, updating an existing post, and deleting a post.
For now, we will use an in-memory array to store the posts data. In the next task, we will replace this with a database and ORM.
Open the app.ts
file and add the following code to create an array of posts:
This code defines a PostType
interface and creates an array of posts with three sample posts. Each post has an id
, content
, and date
field. The id
and date
fields are of type number
which is different from how we defined them in the previous project. This is because we are going to store these in a database using simple data types.
The nextId
variable is used to generate unique IDs for new posts. We start with 4
because the first three IDs are already used by the sample posts.
/posts
Add the following code to the app.ts
file to create an endpoint that returns all posts:
This code creates an HTTP GET endpoint at /posts
that returns the array of posts. The c.json()
method is used to send a JSON response with the posts array.
app.get()
method takes two parameters: the route path and a callback function.c
parameter is an instance of the Context
class, which provides methods for handling the request and response.c.json()
method, which serializes the posts array to JSON format.To test this endpoint, run the server and make a GET request to /posts
using a tool like Postman or cURL.
/posts/:id
Add the following code to the app.ts
file to create an endpoint that returns a specific post by its ID:
This code creates an HTTP GET endpoint at /posts/:id
that takes an id
parameter and returns the post with that ID. If the post is found, it returns the post; otherwise, it returns a 404 error with a JSON response.
Notice how we access the id
parameter using c.req.param("id")
. This is a convenient way to get URL parameters in Hono.js. The parseInt()
function is used to convert the parameter to a number.
The second return statement uses the status code 404
to indicate that the post was not found. The response includes an error message in JSON format. When a response is successful, the status code defaults to 200
.
To test this endpoint, run the server and make a GET request to /posts/2
using a tool like Postman or cURL.
Try making a request to a non-existent post ID to see the error response:
/posts/:id
Add the following code to the app.ts
file to create an endpoint that deletes a post by its ID:
The splice()
method is used to remove the post from the posts
array. The method returns an array of the removed elements, so we access the first element [0]
to get the deleted post.
By convention, the delete
method should return the deleted resource. In this case, we return the deleted post. If the post is not found, we return a 404 error with an error message.
To test this endpoint, run the server and make a DELETE request to /posts/2
using a tool like Postman or cURL.
/posts
Add the following code to the app.ts
file to create an endpoint that creates a new post:
This code creates an HTTP POST endpoint at /posts
that takes a JSON payload with the content
field and creates a new post. The nextId
variable is used to generate a unique ID for the new post.
await c.req.json()
method is used to parse the JSON payload of the request. This method returns a promise that resolves to the parsed JSON object.new Date().getTime()
method is used to get the current timestamp in milliseconds.posts.push(newPost)
method adds the new post to the posts
array.return c.json(newPost, 201)
statement sends a JSON response with the new post and a status code of 201
(Created).We are not doing any input validation in this example, but in a real-world application, you should validate the input data before creating a new post.
To test this endpoint, run the server and make a POST request to /posts
with a JSON payload containing the content
field using a tool like Postman or cURL.
/posts/:id
Add the following code to the app.ts
file to create an endpoint that updates an existing post:
This code creates an HTTP PATCH endpoint at /posts/:id
that updates the content of an existing post. The content
field is extracted from the JSON payload of the request and used to update the post.
posts[postIndex] = { ...posts[postIndex], content }
statement updates the content
field of the post at the specified index.return c.json(posts[postIndex])
statement sends a JSON response with the updated post. This is a common practice to return the updated resource in the response.To test this endpoint, run the server and make a PATCH request to /posts/2
with a JSON payload containing the content
field using a tool like Postman or cURL.
Now that you have implemented the API endpoints for posts, you can test them using Postman. Postman is a popular tool for testing APIs and making HTTP requests. It provides a user-friendly interface for sending requests and inspecting responses.
Create a new collection in Postman and add requests for each of the endpoints you implemented. To create a collection, click on the “New” button in the top-left corner of the Postman window and select “Collection.”
For each request, specify the HTTP method, URL, and any required path parameter or body data. You can also save the responses to inspect them later. When you specify the body data, make sure to select the “raw” option and set the data type to “JSON.”
When you make requests, pay attention to the response status codes and the data returned. This will help you identify any issues with your API implementation.
Currently, all the routes are defined in the app.ts
file. As the application grows, it’s a good practice to separate the routes into individual files for better organization. You can create a routes
directory and move the route handlers into separate files.
Create a new file src/routes/posts.ts
and move the route handlers for posts into it:
In the app.ts
file, import the postsRoute
from the routes/posts.ts
file and register it with the Hono instance:
Notice that we use the app.route()
method to register the postsRoute
with the root path /
. This allows the postsRoute
to handle all requests to /posts
and its subpaths.
This refactoring separates the route handlers for posts into a separate file, making the codebase more modular and easier to maintain. You can follow a similar approach for other routes as well.
In this task, you built the API endpoints for managing posts in the Posts application. You created routes for reading all posts, reading a specific post by ID, creating a new post, updating an existing post, and deleting a post. You used Hono.js to define the routes and handle the requests and responses. You also learned how to test the API endpoints using Postman and how to refactor the code for better organization.