Create a task through the API

Return 201 for a saved task and 422 for invalid input.

Browser practice

Send your first task to the API

Send a blank title, then try a real one. Include done to see which fields the endpoint accepts.

Check your work

A client-supplied done value is ignored on creation. An empty title adds no database row.

Back to roadmap

Build it locally

Laravel 13 · 17 min

Store only validated attributes

In routes/api.php, add the POST route beside your GET route. It reuses their imports. Keep the Task model’s $fillable = ['title'] from the Taskboard course. The database supplies the initial done value, so refresh the record before serializing it.

Route::post('/v1/tasks', function (Request $request) {
    $data = $request->validate(['title' => ['bail', 'required', 'string', 'max:120']]);

    $task = Task::create($data);

    return (new TaskResource($task->refresh()))->response()->setStatusCode(201);
});

Observe both responses

Run these requests in a second terminal after starting Artisan. You should see an object under data for the 201 response, and errors.title for 422.

curl -i 'http://localhost:8000/api/v1/tasks' \
  -H 'Accept: application/json' -H 'Content-Type: application/json' \
  -d '{"title":"Record the API contract"}'

curl -i 'http://localhost:8000/api/v1/tasks' \
  -H 'Accept: application/json' -H 'Content-Type: application/json' \
  -d '{"title":""}'

Practice and verify

Add "done":true to the first payload. The newly created task must still be incomplete, since the create contract accepts only the title. Compare the row count before and after the empty request. It should not change. Keep this local write endpoint off the public internet until you add the owner-scoped authorization from the API access course.

Quick challenge

A request expects JSON but omits title. Which status does Laravel return?

API detectiveChallenge stamp
StoreTaskRequest.php
'title' => ['required', 'string']

Check my work