Developing RESTful APIs with Lumen (A PHP Micro-framework)

Developing RESTful APIs with Lumen (A PHP Micro-framework)

In this tutorial, I’ll show you how easy it is to build and secure an API with Lumen. Lumen is a PHP micro-framework built to deliver micro-services and blazing fast APIs. Learn how to build and secure RESTful APIs with Lumen

In this tutorial, I’ll show you how easy it is to build and secure an API with Lumen. Lumen is a PHP micro-framework built to deliver micro-services and blazing fast APIs. Learn how to build and secure RESTful APIs with Lumen

Lumen is an open-source PHP based micro-framework created by Taylor Otwell in 2015. Lumen is designed for building lightning fast micro-services and APIs. And it opts for maximum speed rather than flexibility in the bootstrapping process. The PHP micro-framework was born out of the need to have light Laravel installations that could be faster than existing PHP micro-frameworks such as Slim and Silex.

Lumen Features And Architecture

Lumen utilizes the Illuminate components that power the Laravel framework. One amazing thing about the way Lumen was built is the fact that you can painlessly upgrade right into Laravel. One of such scenarios where an upgrade process is applicable is when you discover that you need more features out of the box that Lumen doesn’t offer.

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

The entire bootstrap process is located in a single file.

Lumen Key Requirements

In order to use Lumen, you need to have the following tools installed on your machine.

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

Note: You’ll need MySQL for this tutorial. Navigate to the mysql website and install the community server edition. If you are using a Mac, I’ll recommend following these instructions. To avoid micromanaging from the terminal, I’ll also recommend installing a MySQL GUI, Sequel Pro.## Building a Fast Authors API Rapidly With Lumen

At Auth0, we have a number of technical writers, otherwise known as authors. A directive has been given to developing an app to manage Auth0 authors. The frontend app will be built with ReactJS. However, it needs to pull data from a source and also push to it. Yes, we need an API!

This is what we need the API to do:

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

Let’s flesh out the possible endpoints for this API. Given some authors resource, we’ll have the following endpoints:

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

What will be the author attributes? Let’s flesh it out like we did the endpoints.

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

Install Lumen

Run the following command in your terminal to create a new project with Lumen:

composer create-project --prefer-dist laravel/lumen authors


cd into the newly created project.

cd authors


Now, run php -S localhost:8000 -t public to serve the project. Head over to your browser. You should see the index page like so:

Authors Index

Activate Eloquent and Facades

As I mentioned earlier, the entire bootstrap process is located in a single file. Open up the bootstrap/app.php and uncomment this line, // app->withEloquent. Once uncommented, Lumen hooks the Eloquent ORM with your database as configured in the .env file.

Note: You’ll need MySQL for this tutorial. Navigate to the mysql website and install the community server edition. If you are using a Mac, I’ll recommend following these instructions. To avoid micromanaging from the terminal, I’ll also recommend installing a MySQL GUI, Sequel Pro.
In addition uncomment this line //$app->withFacades(); . Once uncommented, we can make use of Facades in our project.

Setup Database, Models and Migrations

At the time of this writing, Lumen supports four database systems: MySQL, Postgres, SQLite, and SQL Server. We are making use of MySQL in this tutorial. First, we’ll create a migration for the Authors table.

Note: You’ll need MySQL for this tutorial. Navigate to the mysql website and install the community server edition. If you are using a Mac, I’ll recommend following these instructions. To avoid micromanaging from the terminal, I’ll also recommend installing a MySQL GUI, Sequel Pro.
Run the command below in the terminal to create the Authors table migration:

php artisan make:migration create_authors_table


The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Lumen to determine the order of the migrations. Next, we’ll modify the recently created migration to accommodate the Authors attributes.

Open up the migration file and modify it like so:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAuthorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email');
            $table->string('github');
            $table->string('twitter');
            $table->string('location');
            $table->string('latest_article_published');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('authors');
    }
}


In the code above, we added the columns to the authors table.

Now, go ahead and run the migration like so:

php artisan migrate


Check your database. You should have the authors and migrations table present.

Let’s create the Author model. Create an app/Author.php file and add the code below to it:

app/Author.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'github', 'twitter', 'location', 'latest_article_published'
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [];
}


In the code above, we made the author attributes mass assignable.

Set up Routes

Routing is straight-forward. Open up routes/web.php and modify it like so:

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/

$router->get('/', function () use ($router) {
    return $router->app->version();
});

$router->group(['prefix' => 'api'], function () use ($router) {
  $router->get('authors',  ['uses' => '[email protected]']);

  $router->get('authors/{id}', ['uses' => '[email protected]']);

  $router->post('authors', ['uses' => '[email protected]']);

  $router->delete('authors/{id}', ['uses' => '[email protected]']);

  $router->put('authors/{id}', ['uses' => '[email protected]']);
});


In the code above, we have abstracted the functionality for each route into a controller, AuthorController. Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Therefore, every route will have a prefix of /api. Next, let’s create the Author Controller.

Set up Author Controller

Create a new file, AuthorController.php in app/Http/Controllers directory and add the following code to it like so:

<?php

namespace App\Http\Controllers;

use App\Author;
use Illuminate\Http\Request;

class AuthorController extends Controller
{

    public function showAllAuthors()
    {
        return response()->json(Author::all());
    }

    public function showOneAuthor($id)
    {
        return response()->json(Author::find($id));
    }

    public function create(Request $request)
    {
        $author = Author::create($request->all());

        return response()->json($author, 201);
    }

    public function update($id, Request $request)
    {
        $author = Author::findOrFail($id);
        $author->update($request->all());

        return response()->json($author, 200);
    }

    public function delete($id)
    {
        Author::findOrFail($id)->delete();
        return response('Deleted Successfully', 200);
    }
}


Let’s analyze the code above. First, we required the Author model, use App\Author. Moving forward, we invoked the necessary methods from the Author model for each controller method. We have five methods here. showAllAuthors, showOneAuthor, create, update and delete.

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

For example, if you make a POST request to /api/authors API endpoint, the create function will be invoked.

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

Finally, test the API routes with Postman.

Author GET operation

Author POST operation

Author PUT operation

Author DELETE operation

Our API works. Awesome!

Lumen API Validation

When developing applications, never trust the user. Always validate incoming data. In Lumen, it’s very easy to validate your application’s incoming data. Lumen provides access to the $this->validate helper method from within Route closures.

Open up the AuthorController file and add modify the create method like so:

...
 public function create(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'location' => 'required|alpha'
        ]);

        $author = Author::create($request->all());

        return response()->json($author, 201);
    }
...


Test the API POST route with Postman.

It validated the incoming requests and returned the appropriate error message.

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

Note: You’ll need MySQL for this tutorial. Navigate to the mysql website and install the community server edition. If you are using a Mac, I’ll recommend following these instructions. To avoid micromanaging from the terminal, I’ll also recommend installing a MySQL GUI, Sequel Pro.
Check out a plethora of validation rules that you can use with Lumen.

Securing the Authors API with Auth0

Right now, anyone can make GET and POST requests to all of the endpoints present in our API. In a real-world scenario, we should restrict POST, DELETE and PUT requests to certain registered and authorized users.

We’ll go ahead and secure some of these API endpoints with JSON Web Tokens.

JSON Web Tokens, commonly known as JWTs, are tokens that are used to authenticate users on applications. This technology has gained popularity over the past few years because it enables backends to accept requests simply by validating the contents of these JWTs. That is, applications that use JWTs no longer have to hold cookies or other session data about their users. This characteristic facilitates scalability while keeping applications secure.

Whenever the user wants to access a protected route or resource (an endpoint), the user agent must send the JWT, usually in the Authorization header using the Bearer schema, along with the request.

When the API receives a request with a JWT, the first thing it does is to validate the token. This consists of a series of steps, and if any of these fails then, the request must be rejected. The following list shows the validation steps needed:

  • Routing: Lumen provides routing out of the box via Fast Route. Fast Route is a library that provides a fast implementation of a regular expression based router.
  • Authentication: Lumen does not support session state. However, incoming requests are authenticated via a stateless mechanism such as tokens.
  • Caching: Lumen supports caching just like Laravel. In fact, there are no differences between using the cache in Lumen and Laravel. Cache drivers such as Database, Memcached, and Redis are supported. You will need to install the illuminate/redis package via Composer before using a Redis cache with Lumen.
  • Errors and Logging: Lumen ships with the Monolog library, which provides support for various log handlers.
  • Queuing: Lumen provides a queuing service that is similar to Laravel’s. It provides a unified API across a variety of different queue back-ends.
  • Events: Lumen’s events provide a simple observer implementation, allowing you to subscribe and listen for events in your application.

We will make use of Auth0 to issue our JSON Web Tokens. With Auth0, we have to write just a few lines of code to get a solid identity management solution, including single sign-on, user management, support for social identity providers (like Facebook, GitHub, Twitter, etc.), enterprise (Active Directory, LDAP, SAML, etc.), and your own database of users.

For starters, if you haven’t done so yet, this is a good time to sign up for a free Auth0 account. Having an Auth0 account, the first thing that we must do is to create a new API on the dashboard. An API is an entity that represents an external resource, capable of accepting and responding to protected resource requests made by clients.

Note: You’ll need MySQL for this tutorial. Navigate to the mysql website and install the community server edition. If you are using a Mac, I’ll recommend following these instructions. To avoid micromanaging from the terminal, I’ll also recommend installing a MySQL GUI, Sequel Pro.
Login to your Auth0 management dashboard and create a new API client.

Click on the APIs menu item and then the Create API button. You will need to give your API a name and an identifier. The name can be anything you choose, so make it as descriptive as you want.

The identifier will be used to identify your API, this field cannot be changed once set. For our example, I’ll name the API, Authors API, and for the identifier, I’ll set it as https://authorsapi.com. We’ll leave the signing algorithm as RS256 and click on the Create API button.

Create a New API

Creating the Authors API

You can define scopes in this section

Head over to your terminal and install Auth0 PHP SDK:

composer require auth0/auth0-php:~5.0


Create a new middleware file, Auth0Middleware.php in the app/Http/Middleware directory. Add the following code to it like so:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth0\SDK\JWTVerifier;

class Auth0Middleware
{
    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!$request->hasHeader('Authorization')) {
          return response()->json('Authorization Header not found', 401);
        }

        $token = $request->bearerToken();

        if($request->header('Authorization') == null || $token == null) {
          return response()->json('No token provided', 401);
        }

        $this->retrieveAndValidateToken($token);

        return $next($request);
    }

    public function retrieveAndValidateToken($token)
    {
        try {
            $verifier = new JWTVerifier([
              'supported_algs' => ['RS256'],
              'valid_audiences' => ['AUTH0_API_AUDIENCE'],
              'authorized_iss' => ['AUTH0_DOMAIN']
            ]);

            $decoded = $verifier->verifyAndDecode($token);
        }
        catch(\Auth0\SDK\Exception\CoreException $e) {
            throw $e;
        };
    }

}


In the retrieveAndValidateToken method, we created an instance of JWTVerifier to verify the token coming from the Authorization header. It checks the algorithm, the API audience, and the issuer to ensure the token is a valid one issued by Auth0.

Note: Replace the AUTH0_API_AUDIENCE and AUTH0_DOMAIN placeholders with the API audience and Auth0 domain values from your Auth0 dashboard.

Now, we want to assign the newly created middleware to our routes. The first step is to assign the middleware a short-hand key in bootstrap/app.php file’s call to the $app->routeMiddleware() method.

Go ahead and open up bootstrap/app.php and uncomment this line of code:

...
// $app->routeMiddleware([
//     'auth' => App\Http\Middleware\Authenticate::class,
// ]);
...


Once uncommented, replace the Authenticate::class with Auth0Middleware::class like so:

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Auth0Middleware::class,
]);


Once the middleware has been defined in the HTTP kernel, as we have done above. We can now use the middleware key in the route options array in the routes/web.php file like so:

...
$router->group(['prefix' => 'api', 'middleware' => 'auth'], function () use ($router) {
  $router->get('authors',  ['uses' => '[email protected]']);

  $router->get('authors/{id}', ['uses' => '[email protected]']);

  $router->post('authors', ['uses' => '[email protected]']);

  $router->delete('authors/{id}', ['uses' => '[email protected]']);

  $router->put('authors/{id}', ['uses' => '[email protected]']);
});


We just secured all the API endpoints with JWT. If a user accesses these API endpoint/route without a valid access token or no token at all, it returns an error. Try it out.

Accessing any endpoint without an authorization header

Accessing any endpoint without any token provided

Accessing any endpoint without a valid access token

Now, let’s test it with a valid access token. Head over to the test tab of your newly created API on your Auth0 dashboard.

Grab the Access token from the Test tab

Grab the Access Token

Now use this access token in Postman by sending it as an Authorization header to make a POST request to api/people endpoint.

Accessing the endpoint securely

It validates the access token and successfully makes the POST request.

Wondering how to integrate the secure API with a frontend? Check out our amazing React and Vue.js authentication tutorials.

Conclusion

Well done! You have learned how to build and secure a rest API with the powerful PHP micro-framework, Lumen, and JWT. Need to use PHP to build your API or micro-service? I’d bet on Lumen as the tool of choice for speed and ease of use.

Check out the repo to get the code.

What the difference between REST API and RESTful API?

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

The short answer is that REST stands for Representational State Transfer. It’s an architectural pattern for creating web services. A RESTful service is one that implements that pattern.

The long answer starts with “sort of” and “it depends” and continues with more complete definitions.

Defining REST

Let’s start by defining what REST is and is not. For some, REST means a server that exchanges JSON documents with a client over HTTP. Not only is that not a complete definition, but it’s also not always true. The REST specification doesn’t require HTTP or JSON. (The spec doesn’t mention JSON or XML at all.)

The Origins of REST

Roy Fielding introduced the REST architectural pattern in a dissertation he wrote in 2000. The paper defines a means for clients and servers to exchange application data. A key feature is that the client doesn’t need to know anything about the application in advance. The link is to chapter five of his paper. While the entire dissertation describes the hows and whys of REST, that chapter defines the architectural pattern.

Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements.

REST’s Architectural Constraints

Here is a summary of the constraints.

  • Client-server – REST applications have a server that manages application data and state. The server communicates with a client that handles the user interactions. A clear separation of concerns divides the two components. This means you can update and improve them in independent tracks.
  • Stateless – servers don’t maintain any client state. Clients manage their application state. Their requests to servers contain all the information required to process them.
  • Cacheable – servers must mark their responses as cacheable or not. So, infrastructures and clients can cache them when possible to improve performance. They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – this constraint is REST’s most well known feature or rule, depending on who you ask. Fielding says “The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.” REST services provide data as resources, with a consistent namespace. We’ll cover this in detail below.
  • Layered system – components in the system cannot “see” beyond their layer. So, you can easily add load-balancers and proxies to improve security or performance.

A RESTful service is more than a web server that exchanges JSON, or any other, documents. These constraints work together to create a very specific type of application.

Applying the Constraints

First, the client-server, layered systems and stateless constraints combine to form an application with solid boundaries and clear separations between concerns. Data moves from the server to the client upon request. The client displays or manipulates it. If the state changes, the client sends it back to the server for storage. Fielding specifically contrasts REST with architectures that use distributed objects to hide data from other components. In REST, the client and server share knowledge about data and state. The architecture doesn’t conceal data, it only hides implementations.

The cacheable and uniform state constraints go one step further. Application data is available to clients in a clear and consistent interface and cached when possible.

So, that’s the technical definition of REST. What does it look like in the real world?

RPC Over HTTP vs. RESTful

Often when someone says that a service “isn’t REST,” they’re looking at the URIs or how the service uses HTTP verbs. They’re referring to REST’s presentation of data as a uniform set of resources.

This distinction is sometimes framed as a difference between remote procedures calls (RPC) and REST. Imagine a web service for listing, adding, and removing, items from an e-commerce inventory.

In one version, there’s a single URL that we query with HTTP GETs or POSTs.  You interact with the service by POSTing a document, setting the contents to reflect what you want to do.

Add new items with a POST with a NewItem:

POST /inventory HTTP/1.1
 
{
    "NewItem": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

Query for items with a POST and an ItemRequest:

POST /inventory HTTP/1.1
 
{
    "ItemRequest": {
          "id": "1001"
      }
}

Some implementations accept a request for a new item with a get, too.

POST /inventory?id=1001 HTTP/1.1

We also change or delete items with a POST and an ItemDelete or ItemUpdate.

POST /inventory HTTP/1.1
 
{
    "ItemDelete": {
          "id": "1001"
      }
}

This isn’t REST. We’re not exchanging the state of resources. We’re calling a function with arguments that happen to be in a JSON document or URL arguments.

A RESTful service has a URI for each item in the inventory.

So, adding a new item would look like the example above.

POST /item HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

But the similarities end there. Retrieving an item is always a GET:

GET /item/1001 HTTP/1.1   

Deleting is a DELETE:

DELETE /item/1001 HTTP/1.1  

Modifying an item is a PUT:

POST /inventory HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "7.99",
          "id": "1001"
      }
}    

The difference is important. In REST, operations that use distinct HTTP actions. These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts. Most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.

The critical point is that the URIs operate on the data, not on remote methods.

But there’s another reason why the resource model is essential.

REST vs RESTful and the Richardson Maturity Model

When you model your URIs after resources and use HTTP verbs you make your API predictable. Once developers know how you defined your resources, they can almost predict what the API looks like. Here again, the emphasis is on understanding the data, not the operations.

But even if you can’t make the API entirely predictable, you can document any REST service with hypertext. So, each item returned in the inventory app would contain links for deleting, modifying, or setting the inventory level of the resource. Fielding says that before a service is RESTful, it must provide hypertext media as part of the API.

Many sites don’t meet this requirement but are still called REST. Fact is, many sites break the rules in one way or another. So many that Leonard Richardson created a model breaks down REST into levels of compliance

We’ve already covered the source levels:

  • 0 – exporting an API over HTTP with methods called with arguments
  • 1 – Exporting resources instead of methods
  • 2 – Proper use of HTTP verbs
  • 3 – Exporting hypertext with objects that make all or part of the API discoverable.

Richardson’s model is his own, and it doesn’t map directly into Fielding’s spec. Since Fielding requires level three, he would say that most apps aren’t REST anyway.

The point is many services that we colloquially refer to as REST, technically aren’t.

REST vs RESTful: Does It Matter?

So, does the REST vs. RESTful comparison matter? Probably not. How well your architecture complies with an arbitrary standard isn’t as important with how well it suits your needs and can grow with your business.

The REST architectural pattern has many advantages. Fielding designed it for the web and, 18 years later, most of the constraints he had in mind are still with us. In 2000 we didn’t have Android or the iPhone. IE5 had 50% of the browser market share. It’s biggest rival was Firefox. But Fielding recognized what online applications needed and how web clients would evolve from HTML display engines into complete applications. The tools we use today have grown to suit REST, not the other way around.

Thank you for reading. Hope this tutorial will help you!

Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]