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.
JSON (JavaScript Object Notation) is a popular format for sending data. Here’s an example for our ToDo item:
JSON1{ 2 "title": "Finish Homework", 3 "description": "Complete math and science homework" 4}
Retrieve and decode the JSON data from the request body:
php1/** 2* @Route("/todos", name="create_todo", methods={"POST"}) 3*/ 4public function create(Request $request): JsonResponse 5{ 6 $data = json_decode($request->getContent(), true); 7 8 if (empty($data['title'])) { 9 return new JsonResponse(['error' => 'Title is required'], 400); 10 } 11 12 $todo = $this->todoService->create($data); 13 return new JsonResponse($todo, 201); 14}
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.
Extract specific parts of the ToDo item from the decoded JSON:
php1public function create(array $data): array 2{ 3 $todos = $this->findAll(); 4 5 $id = count($todos); 6 7 $todo = [ 8 'id' => $id, 9 'title' => $data['title'], 10 'description' => $data['description'] ?? null 11 ]; 12 13 $todos[] = $todo; 14 15 $this->session->set('todos', $todos); 16 17 error_log("Session after adding todo: " . json_encode($this->session->get('todos', []))); 18 19 return $todo; 20}
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.
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!