Build simple REST API with PHP – Part 2

In our first part of this post series we saw how to bootstrap our API and we defined the end points for it. Now, we’ll add the necessary logic to make our end points to work.

End Points

GET /users

Here we will get ALL our existing users.

1
2
3
4
5
6
7
8
9
10
11
12
13
// GET route for all users
$app->get('/users', function () use ($app, $log) {
    $users = array();
    $results = \ORM::forTable('user');

    $users = $results->findArray();

    // Here, we can add sorting, filtering and/or searching logic

    $output = array('code' => 200, 'data' => $users);
    echo json_encode($output, JSON_PRETTY_PRINT);
    return;
});

 

GET /users/:id

Given a user ID we return that user if exists, if not we return a 404 error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// GET route
$app->get('/users/:id', function ($id) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $user = $user->asArray();
           
        $output = array('code' => 200, 'data' => array($user));
        echo json_encode($output, JSON_PRETTY_PRINT);
        return;
    }
   
    $app->notFound();
});

Observe how the “:id” url parameter is passed as an argument of the callable function.

 

POST /users

Now, sending POST data to the /users end point we will be able to create a new User.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// POST route, for creating
$app->post('/users', function () use ($app, $log) {
    // Get POSTed data in body
    $body = $app->request()->getBody();

    // Validate data here

    $user = \ORM::for_table('user')->create();
    $user->set($body);
    if ($user->save() === true) {
        $output = array(
            'code' => 200,
            'data' => array($user->asArray())
        );
    echo json_encode($output, JSON_PRETTY_PRINT);
        return;
    } else {
        throw new \Exception('Something went wrong.');
    }
});

 

PUT /users/:id

Update an existing user with passed data given a user ID.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// PUT route, for updating
$app->put('/users/:id', function ($id) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $body = $app->request()->getBody();

        // Validate data here

        $user->set($body);
        if ($user->save() === true) {
            $user = $user->asArray();
           
            $output = array('code' => 200, 'data' => array($user));
            echo json_encode($output, JSON_PRETTY_PRINT);
            return;
        } else {
            throw new \Exception('Something went wrong.');
        }
    }
   
    $app->notFound();
});

 

DELETE /users/:id

Here given a user ID we will delete the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// DELETE route
$app->delete('/users/:id', function ($id) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $user->delete();
        if ($user->save() === true) {
            $output = array('code' => 200, 'data' => array());
            echo json_encode($output, JSON_PRETTY_PRINT);
            return;
        } else {
            throw new \Exception('Something went wrong.');
        }
    }
   
    $app->notFound();
});

 

User’s Phonenumbers

Now, we will define the end points for our second collection Phonenumbers.

GET /users/:id/phonenumbers

In this end point we will return all the associated phonenumbers to a user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// GET route for all users's phonenumbers
$app->get('/users/:id/phonenumbers', function ($id) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $data = $user->asArray();
        $phonenumbers = \ORM::forTable('phonenumber')
            ->where('user_id', $id)
            ->orderByDesc('id')
            ->findArray();
        $data['phonenumbers'] = $phonenumbers;
        $output = array('code' => 200, 'data' => $data);
        echo json_encode($output, JSON_PRETTY_PRINT);
        return;
    }
   
    $app->notFound();
});

 

GET /users/:id/phonenumbers/:pid

Now given a user ID and a phone ID we will return that specific phonenumber for the given user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// GET route for specific user's phonenumber
$app->get('/users/:id/phonenumbers/:pid', function ($id, $phoneId) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $data = $user->asArray();
        $phonenumber = \ORM::forTable('phonenumber')
            ->where('user_id', $id)
            ->andWhere('id', $phoneId)
            ->findOne();
        if ($phonenumber) {
            $data['phonenumber'] = $phonenumber;
            $output = array('code' => 200, 'data' => $data);
            echo json_encode($output, JSON_PRETTY_PRINT);
            return;
        }
    }
   
    $app->notFound();
});

 

POST /users/:id/phonenumbers

With this end point we will be able to create/add a phonenumber to a user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// POST route, for creating a new user's phonenumber
$app->post('/users/:id/phonenumbers', function ($id) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $data = $user->asArray();
        // Get POSTed data in body
        $body = $app->request()->getBody();

        // Validate data here

        $phonenumber = \ORM::for_table('phonenumber')->create();
        $phonenumber->set($body);
        if ($phonenumber->save() === true) {
            $data['phonenumber'] = $phonenumber->asArray();
            $output = array(
                'code' => 200,
                'data' => $data
            );
        echo json_encode($output, JSON_PRETTY_PRINT);
            return;
        } else {
            throw new \Exception('Something went wrong.');
        }
    }
   
    $app->notFound();
});

 

PUT /users/:id/phonenumbers/:pid

PUT route to update a user’s phonenumber.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// PUT route, for updating a user's phonenumber
$app->put('/users/:id/phonenumbers/:pid', function ($id, $phoneId) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $data = $user->asArray();
        $phonenumber = \ORM::forTable('phonenumber')
            ->findOne($phoneId);

        if ($phonenumber) {
            $data = $user->asArray();
            // Get POSTed data in body
            $body = $app->request()->getBody();

            // Validate data here

            $phonenumber->set($body);
            if ($phonenumber->save() === true) {
                $data['phonenumber'] = $phonenumber->asArray();
                $output = array(
                    'code' => 200,
                    'data' => $data
                );
            echo json_encode($output, JSON_PRETTY_PRINT);
                return;
            } else {
                throw new \Exception('Something went wrong.');
            }
        }
    }
   
    $app->notFound();
});

 

DELETE /users/:id/phonenumbers/:pid

And at the end, we define the route to delete an specific user’s phonenumber.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// DELETE route, for delete a user's phonenumber
$app->delete('/users/:id/phonenumbers/:pid', function ($id, $phoneId) use ($app, $log) {
    $user = \ORM::forTable('user')
        ->findOne($id);

    if ($user) {
        $phonenumber = \ORM::forTable('phonenumber')
            ->findOne($phoneId);
        if ($phonenumber) {
            $phonenumber->delete();
            if ($phonenumber->save() === true) {
                $output = array('code' => 200, 'data' => array());
                echo json_encode($output, JSON_PRETTY_PRINT);
                return;
            } else {
                throw new \Exception('Something went wrong.');
            }
        }
    }
   
    $app->notFound();
});

 

Well, we finished defining all our end points to interect against our API. At this point we have a basic API working but still there are thing to do to make it more fully functional. For instance, what if we want to make our API secure? We should add authentication, and we’ll do it using really great Slim’s functionality Middlewares. Also, we can ensure all our requests/responses are being talking JSON and/or add some rate limit to don’t allow overwhelming our API.

In the next and last post we will cover all this. See you soon! :D.

share it...Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Pin on PinterestDigg thisEmail this to someone

Leave a Comment.