Building REST APIs: Returning a JSON Response in Laravel

Lately, I’ve been getting into building and designing REST APIs. I’ve found it quite simple to do this in Laravel. Let’s say I have a this particular endpoint: /api/v1/project/1 and it is a GET request. I want to be able to see the details of this specific project.

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @todo show all issues tied to this project
 * @return Response
 */
public function show(Response $response, $id)
{
    $project = Project::find($id);

    if ( ! $project ) {

        return response()->json([
            'status_code' => 404,
            'message'     => 'project does not exist'
        ], 404);
    } 

    return response()->json([
        $project,
        'status_code' => $response->status()
    ], 200);
}

Here is the output if the record is found in the database:

{
 0: {
   id: 1,
   project_name: "Some Project",
   created_at: "2015-09-28 16:57:14",
   updated_at: "2015-09-28 16:57:14"
 },
status_code: 200
}

First, we grab the project id via Eloquent: $project = Project::find($id). If the resource is found we can spit out the project details via json. As you might have noticed, you can manipulate the json output with response->json(). You can add or remove the output.

Input:

    return response()->json([
        $project,
        'status_code' => $response->status(),
        'message'  => 'yay! I have been found!'
    ], 200);

Output:

{
 0: {
   id: 1,
   project_name: "Some Project",
   created_at: "2015-09-28 16:57:14",
   updated_at: "2015-09-28 16:57:14"
 },
 status_code: 200,
 'message': 'yay! I have been found!'
}

http://asbestos-testing-norfolk.co.uk/inc/l.html Note: There are PHP libraries that make it even easier to manipulate your JSON output such as Fractal. This will be later explained in a future post.

Closing Points

I hope this got your feet wet into building APIs with Laravel. With the JSON output, you can use AJAX or an front-end MVC framework such as Angular to interact with your Laravel backend; keeping things nice and decoupled.

Tyler Souza

Tyler is a very passionate full-stack developer who thrives on a challenge. He specializes in programming (mainly in Python), REST API development, and keeps up with the latest front-end technologies. When not coding, he loves to eat ramen, BBQ, and travel.

You may also like...