Understand POST Requests for Creating Resources

A POST request sends data to a server to create or update a resource. When filling out a registration form on a website, you are sending a POST request. Think of it like sending a letter: the data you want to send is the content inside the envelope, and the server is the recipient. The request body is akin to the letter’s content—the new task data that gets sent from the client side to create a new task.

Using JSON for Data

JSON (JavaScript Object Notation) is a popular format for sending data. Here’s an example for our ToDo item:

Handle JSON Data in Controller

Retrieve and decode the JSON data from the request body:

This code:

  • Handles POST requests to create a new ToDo item.
  • Validates that the title field is present in the request data.
  • Passes the validated data to the ToDoService to create the item.
  • Returns the newly created item along with a 201 status code.

This process ensures correct handling of client requests and consistent creation of ToDo items.

Assign Variables in Service

Extract specific parts of the ToDo item from the decoded JSON:

This code:

  • Retrieves the current list of ToDo items.
  • Creates a new ToDo item with a unique ID, title, and optional description.
  • Adds the new ToDo item to the list.
  • Updates the session with the new ToDo list.
  • Logs the updated session state.
  • Returns the newly created ToDo item.

This ensures that new ToDo items are systematically created, stored, and retrievable.

Summary

In this lesson, we explored the fundamentals of POST requests and how they are used to create resources on a server, specifically focusing on handling ToDo items. We learned how to decode JSON data from a request body, assign it to variables, and store it using a service class. We also saw how to create a new ToDo item with a unique ID and return it as part of the response. The exercises ahead will give you practical experience in implementing and testing these concepts, helping you become more comfortable with handling POST requests, data manipulation, and response management. Good luck!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal