This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

CloudwaysCDN — a powerful solution that offers superior performance and satisfied global audience for your business. Read More

Create REST API in Silex with User Authentication

Updated on  May 14, 2018

10 Min Read
Reading Time: 10 minutes

When you are working with cross-device applications you need to develop a REST API to interact with the application smoothly. Although you can go with web services, using REST API in Silex with user authentication is a much more secure and practical. In a previous article, I covered a Slim based REST API in detail. In essence, REST API acts as a bridge or medium between data resources and the application interface, irrespective of the devices.

rest api in silex

In this article, I am going to develop a simple REST API using Silex framework. The API will first authenticate the user. Once authenticated, the user can perform further actions. This article will cover the following topics:

  • Silex Framework installation
  • HTTP Codes
  • Middleware
  • Developing the REST API
    • Install Eloquent in Silex
    • Create User and Message Models
    • Create Routes and Perform API Actions
      • Retrieving User Messages
      • Retrieving the Messages of a Single User
      • Create a New Message via Post
      • Update the Message via PUT
      • Delete the Message via Delete
  • Conclusion

You can also find the complete code of this REST API on Github. Just clone it and import the database.

All you need to develop this API is a code editor, Composer, and Postman. My main focus in this tutorial is the background service so I will not be doing much work on the views. For the purpose of this article, I assume that you have launched a PHP stack server on Cloudways. If not consult the following GIF for more details:

Understanding Silex Framework

Silex is a PHP microframework built with Symfony components and Pimple. The framework is ideal for single-page applications. Silex has an extension system based around the Pimple micro service container that makes it even easier to tie in third party libraries. It uses the Symfony HTTPKernel to request and respond to HTTP requests. For more detailed discussion on Silex framework, check out this detailed guide.

The composer is the most proper way of installing Silex. For this, go to your project folder using this command:

Next, execute the following command:

Alternatively, If you do not wish to install it from the Composer, you can download Silex 2 from here.

Once Silex has been successfully installed, I will next edit the autoload.php and initialize Silex in the application through index.php.

Now to run the application,  add $app-> run() at the very end of the application before closing the PHP tags. All the code will be reside before the above $app-> run().

HTTP Codes

Silex makes use of the HTTP codes extensively while sending and receiving responses. Thus,  You should be aware of HTTP codes while working with REST API in Silex. Following is the list of some of the most common codes that I will use in the REST API code:

HTTP Code Description
200 OK
201 Created
204 No Content
400 Bad Request
401 UnAuthorized
403 Forbidden
404 Not Found
500 Internal Server error

For more detailed coverage of HTTP codes, check out this article.


Silex allows you to run the code, that altered the default behavior of Silex, at different stages during the handling of a request through middleware. This Middleware can run before and after the matching route. I will use middleware to check whether a user exists in the database. Silex provides two types of middlewares: Application and Route.

Developing the REST API

Let’s get started with the real scenario of this tutorial.

First, you need to import tables in the demo database that contain both the user and the messages tables.  Copy the following SQL code and run it in the SQL box in the database:

This query will create the tables and insert the dummy data. The next step is to install the ORM to communicate with the tables.

php hosting signup

Install Eloquent in Silex

I will use Laravel’s Eloquent in Silex. The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with the database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in the tables, as well as insert new records into the table.

Eloquent can be installed and use independently. To install it, run the following Composer command:

Once the Eloquent ORM is successfully installed, create a file connection.php for establishing a connection with the database.Remember you need to add your database credentials (available in the Application Access area of the Cloudways Admin).

Open connection.php and add the following code to it:

The connection will be established now. The next step is to create the Models of the tables.

Create User and Message Models

When you install Silex, you just got the vendor folder and some composer files. You need to add the src folder in the root, and then add a Todo folder. The Todo folder contains two more sub folders, Models and Middleware.

Create Authentication.php in the Middleware folder. Similarly, the Model folder will contain Message.php and User.php files (check the image below)

As I explained earlier, each database table has a corresponding “Model” which is used to interact with that table. I will now add the Message class in Message.php, which will extend the Eloquent models.

This is a simple class with no code. Now, I shall add the User class in the User.php. However, before doing it, I  am going to authenticate the user by wiring up a middleware. Open the Authenticate.php file and add the Authentication class in it.

This class contains an authenticate() method which gets the header information and saves the API key from the header. This API key will be used in the User model which also has an authenticate() function taking apikey as an argument. If the API key is not found, a 401 HTTP error code (user is not authorized) will be generated.

Next, I saved the user id in $request->attributes->set(‘userid’,$check); variable which I will use to get selected user’s messages.

Now open the User.php. I will use the above API key to retrieve user information using Eloquent.

In the first line of this code, I get the the user from the database. This line  $user = User::where('apikey', '=', $apikey)->take(1)->get(); generates a query similar to the SQL query select * from the users where apikey = $apikey. Next, it returns the details of the user that will then be used for getting messages.

At this point, I have finalized the models and the middleware. Now, I am going to create the routes and perform REST actions for user based messages.

Create Routes and Perform API Actions

Previously, I initialized Silex In index.php file. Now the code in this file will be extended to include the connection file,Request/Response component, Models and Middleware.

I need to set up the authentication middleware before every action. I am using the before application middleware which allows me to tweak the Request before the controller is executed.

Retrieving User Messages

I will get the messages of the user with the get() request. Remember, I have saved the user id in the User model, which I am going to pass here to get the messages.

I will save the necessary details in $payload array and return the encoded data. Here, I am using Postman to test out the API. First, I am getting the messages without the apikey. It should give a 401 unauthorized error from the User model.

Now, let’s pick the apikey of a user from the database and add in the Authorization value. The user messages are now retrieved.

So now that the testing is done, I am getting messages by authenticating a user with his/her apikey.

Retrieving the Messages of a Single User

Now, if you want to retrieve the messages of a single user, simply pass the message ID with /message route (use the syntax /message/{message_id}). Similarly, I will use the payload array to show the record.

Simply pass the message id in where() to retrieve the matching message.

Create a New Message via Post

Now I will create a new message for the current authenticated user by getting the message value and passing the userid. The Eloquent save() method will then create a new message in the database.

For instance, I will check whether the selected message ID exists. Next, I will pass the message_id and message_uri to $payload array with a 201 code. If the message creation fails, a 400 error code will be generated.

This will get the message and the route from which the message is created.

Update the Message via PUT

Next, I will try to update a previously created message by getting the message value as a parameter and the message ID from the route.

Delete the Message via Delete

The last action of the API is to delete the user message. For this, I need to pass the message ID and the delete() method will take care of the deletion of record. In the event of success, a 204 response code is returned.


REST API is a great solution for creating cross-device applications. It provides a set of HTTP codes through which the developer could easily identify the flow of data. In this article, I explained how to make REST API in Silex that integrates user authentication as a core component.

If you have a question about the topic, do leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Start Growing with Cloudways Today.

Our Clients Love us because we never compromise on these

About The Author

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at

Stay Connected:

Get Our Newsletter
Be the first to get the latest updates and tutorials.