Welcome back! You can already create tickets with POST, retrieve them with GET, and confirm that new rows persist in PostgreSQL. Now you’ll complete the core ticket lifecycle by updating existing resources with PATCH and removing them with DELETE.
You’ll define a partial-update contract, validate only the fields supplied by the client, construct a safe dynamic UPDATE statement, and return the latest database representation. You’ll also implement deletion with precise REST semantics: 204 No Content when a ticket is removed and 404 Not Found when the target does not exist.
Previously, POST /api/tickets accepted a JSON body, created a server-owned identifier, inserted a new row, and returned 201 Created. This lesson continues from that flow by targeting an existing ticket through /api/tickets/:ticketId.
The :ticketId segment is a route parameter. For this request:
text
PATCH /api/tickets/tkt_1012
Express exposes "tkt_1012" through request.params.ticketId.
A PATCH request also carries a JSON body describing the fields that should change:
JSON
{ "priority": "high", "status": "in_progress"}
A DELETE request needs no JSON body. The ticket ID in the URL is enough to identify the resource to remove.
These values come from different parts of the request:
Route parameter: identifies which ticket is targeted.
JSON body: describes the partial changes for PATCH.
Query parameters: continue to control collection filtering and sorting, but are not involved in these detail mutations.
PATCH Compared with PUT
PATCH represents a partial update. The client sends only the fields that should change, and every omitted property keeps its current value.
For example:
JSON
{ "priority": "high"}
This request should change only priority. It must not reset the title, description, status, requester, or timestamps.
A full replacement operation is commonly represented by PUT, where the client supplies the complete replaceable representation. This project uses PATCH because ticket edits are naturally partial and clients should not need to resend unchanged fields.
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Defining the Partial-Update Contract
The update model lives in src/domain/ticket.ts. Every property is optional because a valid patch can update one field or several fields.
title, description, priority, and status are the only properties this endpoint allows clients to update. The narrow interface prevents unrelated fields from becoming part of the repository contract.
Every property is optional because PATCH does not require a complete ticket. A request containing only status should leave the other values unchanged.
Server-owned and relationship fields are intentionally absent. Clients cannot change id, requesterId, assigneeId, createdAt, or updatedAt through this general update operation.
priority and status reuse the existing domain unions. Once the route has validated their runtime values, the repository receives only supported options.
This interface describes normalized repository input, not raw HTTP data. The route still needs to validate request.body before constructing it.
Validating Only Supplied Fields
The PATCH handler in src/routes/ticket-routes.ts begins with an empty patch object.
const body = request.body as Record<string, unknown>;const patch: UpdateTicketInput = {};
The incoming JSON remains untrusted, so its properties are treated as unknown. TypeScript cannot guarantee that an external client sent strings or valid domain values.
The route copies only recognized, validated fields into patch. Unknown properties are not forwarded to the repository or turned into SQL assignments.
Each supported field is handled independently. The title follows the same normalization rule used during creation.
if (body.title !== undefined) { if (typeof body.title !== "string" || body.title.trim().length < 3) { response.status(400).json({ error: { code: "INVALID_BODY", message: "title must contain at least 3 characters.", }, }); return; } patch.title = body.title.trim();}
The validation runs only when title is present. Omitting it means “leave the current title unchanged.”
A supplied title must be a string with at least three non-whitespace characters. The normalized value is then added to the patch object.
The early return prevents invalid input from reaching the repository. No SQL update occurs after this response is sent.
The optional description is also checked and trimmed.
if (body.description !== undefined) { if (typeof body.description !== "string") { response.status(400).json({ error: { code: "INVALID_BODY", message: "description must be a string.", }, }); return; } patch.description = body.description.trim();}
An empty string is allowed because the contract permits clearing a ticket’s description.
Other JSON types are rejected instead of being silently converted into text.
Validating Status and Priority
The route validates domain values against the same constants used by ticket creation and collection filtering.
if (body.priority !== undefined) { if (!ticketPriorities.includes(body.priority as TicketPriority)) { response.status(400).json({ error: { code: "INVALID_BODY", message: "priority is not supported.", }, }); return; } patch.priority = body.priority as TicketPriority;}if (body.status !== undefined) { if (!ticketStatuses.includes(body.status as TicketStatus)) { response.status(400).json({ error: { code: "INVALID_BODY", message: "status is not supported.", }, }); return; } patch.status = body.status as TicketStatus;}
Priority is restricted to "low", "medium", or "high". A value such as "urgent" receives HTTP 400.
Status is restricted to "open", "in_progress", or "closed". The shared constants prevent the creation and update routes from drifting into different rules.
The type assertions do not perform validation themselves. They become safe only after the runtime includes() checks succeed.
Rejecting Empty Updates
Although every individual field is optional, a public PATCH request must contain at least one supported update.
if (Object.keys(patch).length === 0) { response.status(400).json({ error: { code: "INVALID_BODY", message: "At least one update field is required.", }, }); return;}
An empty body such as {} does not describe any change. Returning 400 Bad Request gives the client a clear explanation rather than performing a meaningless database operation.
A body containing only unknown fields also leaves patch empty. Since only whitelisted fields are copied, unsupported input cannot silently reach the SQL builder.
The repository still handles an empty patch safely, but the public route rejects it as part of the HTTP contract.
Building a Safe Dynamic UPDATE
Handling an Empty Repository Patch
The repository includes a defensive branch before creating the UPDATE statement.
if (assignments.length === 0) { return findTicketById(id);}
An empty assignment list would produce invalid SQL such as UPDATE tickets SET , updated_at = now(). The guard prevents that statement from being constructed.
Instead, the repository returns the current ticket when it exists or null when it does not.
The public route normally rejects empty patches first. This repository behavior still makes the persistence function safe if another internal caller supplies an empty object.
Updating the Timestamp and Returning the Fresh Row
After the assignments are ready, the repository appends the ticket ID as the final parameter and performs the update.
values.push(id);const result = await query<TicketRow>( `UPDATE tickets SET ${assignments.join(", ")}, updated_at = now() WHERE id = $${values.length} RETURNING id, title, description, status, priority, requester_id, assignee_id, created_at, updated_at`, values,);
The ticket ID is appended last, so its placeholder is always based on the final parameter-array length. With two changed fields, the ID becomes $3.
assignments.join(", ") creates the comma-separated SET clause. Because all assignments came from the fixed whitelist, only approved columns can appear.
updated_at = now() records when the mutation occurred. PostgreSQL remains the source of truth for timestamps rather than relying on the application server’s clock.
WHERE id = ... limits the mutation to the requested ticket. If the ID does not match a row, PostgreSQL returns no records.
RETURNING provides the complete updated representation in the same database round trip. The route can send the final stored row without issuing a separate SELECT.
The result is mapped into the public ticket shape:
The target ID comes from the URL, while the changes come from the body. The handler keeps those two request concerns separate.
A successful update returns HTTP 200 with the complete updated ticket. The response includes both changed and unchanged fields.
A missing ID returns the same focused TICKET_NOT_FOUND envelope used by the detail GET route.
Returning the repository result lets the client immediately see the new updatedAt value generated by PostgreSQL.
Grouping Detail Methods with router.route()
GET, PATCH, and DELETE operate on the same resource path. Express allows them to be grouped with router.route().
ticketRoutes.route("/:ticketId") .get(async (request, response) => { // Fetch one ticket. }) .patch(async (request, response) => { // Validate and update one ticket. }) .delete(async (request, response) => { // Delete one ticket. });
The shared path appears once, making it clear that all three methods operate on the same ticket resource.
Express selects the correct handler from the HTTP method. A GET request does not run the PATCH or DELETE logic.
Grouping changes the router’s organization, not the public URLs. Existing detail requests continue to use /api/tickets/:ticketId.
Deleting a Ticket in PostgreSQL
The deletion repository function is intentionally small.
export async function deleteTicket(id: string): Promise<boolean> { const result = await query( "DELETE FROM tickets WHERE id = $1", [id], ); return result.rowCount === 1;}
The target ID uses $1 and a separate parameter array. Route input is not interpolated into the SQL string.
PostgreSQL’s rowCount reports how many rows were removed. A value of 1 means the ticket existed and was deleted.
A value of 0 means no ticket matched the supplied ID. The repository converts that database detail into a simple boolean for the route.
The repository does not need to fetch the ticket first. The DELETE statement itself determines whether a row existed.
Returning 204 No Content
The route maps the boolean result to the appropriate HTTP response.
if (!(await deleteTicket(String(request.params.ticketId)))) { response.status(404).json({ error: { code: "TICKET_NOT_FOUND", message: "Ticket not found.", }, }); return;}response.status(204).send();
A false result becomes HTTP 404 because the requested resource did not exist.
A successful deletion returns 204 No Content. The status code completely communicates that the request succeeded and there is no representation to send.
The endpoint deliberately does not return the deleted ticket or a JSON success envelope. A correct 204 response has an empty body.
Repeating the same DELETE returns 404, because the first successful request changed the persistent database state.
Testing PATCH in the API Simulator
Keep the base URL set to:
http://localhost:4000
Start by sending:
GET /api/tickets
Copy the ID of a ticket you want to inspect. For mutation testing, it is safer to create a disposable ticket first with POST /api/tickets so the deterministic seeded records remain available for later exercises.
Switch the method to PATCH and use the copied ID in the path:
/api/tickets/<copied-id>
Open Body, select JSON, and enter:
{ "priority": "high", "status": "in_progress"}
Use Beautify when needed to format the body, then send the request.
The response should contain the updated ticket with:
"priority": "high"
"status": "in_progress"
A newer updatedAt
All omitted fields preserved
Send a later GET to the same path to confirm that PostgreSQL persisted the changes.
Testing Partial-Update Behavior
A one-field patch should update only that field:
{ "description": "Updated through PATCH."}
Afterward, the ticket’s title, priority, and status should remain unchanged.
A multi-field patch can update several approved properties together:
{ "title": "Updated support request", "priority": "low", "status": "closed"}
Invalid requests should be rejected before SQL runs:
{}
{ "priority": "urgent"}
{ "title": "Hi"}
Each should return HTTP 400 with an INVALID_BODY response.
Testing DELETE Safely
Create a disposable ticket through POST /api/tickets, copy its returned ID, and confirm it exists with:
GET /api/tickets/<id>
Then switch the API Simulator method to DELETE. Keep the same URL and send the request without a body.
The response should show:
204 No Content
The response body should be empty. Send another GET or repeat the DELETE against the same ID, and the API should return:
{ "error": { "code": "TICKET_NOT_FOUND", "message": "Ticket not found." }}
This lifecycle demonstrates persistent behavior:
POST → PATCH → GET → DELETE → GET
The ticket is created, updated, retrieved from PostgreSQL, removed, and then no longer found.
Recap
You’ve completed the core CRUD lifecycle for tickets. PATCH uses the route parameter to identify the resource and a JSON body to describe only the supplied changes. The route validates and normalizes those fields, while the repository constructs assignments from a fixed whitelist and keeps all request values in PostgreSQL placeholders.
A successful update returns the fresh row with a database-generated updatedAt. A successful deletion returns 204 No Content, while missing update and deletion targets return 404 TICKET_NOT_FOUND.
With GET, POST, PATCH, and DELETE now working together, the ticket API supports complete resource creation, retrieval, partial modification, and removal while preserving safe SQL construction and clear HTTP semantics.
const body = request.body as Record<string, unknown>;const patch: UpdateTicketInput = {};
TypeScript
if (body.title !== undefined) { if (typeof body.title !== "string" || body.title.trim().length < 3) { response.status(400).json({ error: { code: "INVALID_BODY", message: "title must contain at least 3 characters.", }, }); return; } patch.title = body.title.trim();}
TypeScript
if (body.description !== undefined) { if (typeof body.description !== "string") { response.status(400).json({ error: { code: "INVALID_BODY", message: "description must be a string.", }, }); return; } patch.description = body.description.trim();}
TypeScript
if (body.priority !== undefined) { if (!ticketPriorities.includes(body.priority as TicketPriority)) { response.status(400).json({ error: { code: "INVALID_BODY", message: "priority is not supported.", }, }); return; } patch.priority = body.priority as TicketPriority;}if (body.status !== undefined) { if (!ticketStatuses.includes(body.status as TicketStatus)) { response.status(400).json({ error: { code: "INVALID_BODY", message: "status is not supported.", }, }); return; } patch.status = body.status as TicketStatus;}
TypeScript
if (Object.keys(patch).length === 0) { response.status(400).json({ error: { code: "INVALID_BODY", message: "At least one update field is required.", }, }); return;}
Unlike ticket creation, a partial update does not know in advance which columns will be changed. The repository in src/repositories/ticket-repository.ts builds the assignment list from a fixed whitelist.
Only supplied properties produce assignments. An omitted property never appears in the SQL statement and therefore keeps its stored value.
The database column strings are fixed application code. Even though the SQL statement is dynamic, its structure is limited to a small trusted whitelist.
Every request-derived value remains in PostgreSQL’s parameter array. This preserves the same injection protection used by the earlier lookup, filter, and creation queries.
For this patch:
{ "priority": "high", "status": "in_progress"}
the generated pieces are conceptually:
priority = $1, status = $2
["high", "in_progress"]
TypeScript
if (assignments.length === 0) { return findTicketById(id);}
TypeScript
values.push(id);const result = await query<TicketRow>( `UPDATE tickets SET ${assignments.join(", ")}, updated_at = now() WHERE id = $${values.length} RETURNING id, title, description, status, priority, requester_id, assignee_id, created_at, updated_at`, values,);
ticketRoutes.route("/:ticketId") .get(async (request, response) => { // Fetch one ticket. }) .patch(async (request, response) => { // Validate and update one ticket. }) .delete(async (request, response) => { // Delete one ticket. });
TypeScript
export async function deleteTicket(id: string): Promise<boolean> { const result = await query( "DELETE FROM tickets WHERE id = $1", [id], ); return result.rowCount === 1;}
TypeScript
if (!(await deleteTicket(String(request.params.ticketId)))) { response.status(404).json({ error: { code: "TICKET_NOT_FOUND", message: "Ticket not found.", }, }); return;}response.status(204).send();
text
http://localhost:4000
text
GET /api/tickets
text
/api/tickets/<copied-id>
JSON
{ "priority": "high", "status": "in_progress"}
JSON
{ "description": "Updated through PATCH."}
JSON
{ "title": "Updated support request", "priority": "low", "status": "closed"}
JSON
{}
JSON
{ "priority": "urgent"}
JSON
{ "title": "Hi"}
text
GET /api/tickets/<id>
text
204 No Content
JSON
{ "error": { "code": "TICKET_NOT_FOUND", "message": "Ticket not found." }}