Download the PHP package webiny/rest without Composer

On this page you can find all versions of the php package webiny/rest. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package rest

REST Component

A simple but powerful REST library that doesn't get in the way.

Install the component

The best way to install the component is using Composer.

For additional versions of the package, visit the Packagist page.

Usage

Some of the built-in features:

Usage example

Configuration and dependencies

This is an example configuration:

As you can see, you can have multiple REST configurations. The minimum that one configuration must have is just the definition of CompilePath.

Configuration parameters:

CompilePath

This is the absolute path to a folder where the REST component will store the compiled files.

If you want to know more: When you register a class, or in API naming, a "service", the component will parse through that class and all its methods and their annotations, which would be then evaluated based on different rules, to define the service behaviour. All this is then saved an array that is actually stored in a file, that we call the compile cache file.

Router

This is an optional setting, it tells to the Rest component how it should transform the current url to get the service class name. However to trigger that mechanism, the url must match the Path parameter. Variables in brackets will act as patterns to match certain parts of the url. Those matches can then be used to create the Class name. You will find more about routing in the Routing and accessing the APIs section.

Cache

As stated before, the component uses the Cache component from Webiny Framework. The value of the Cache should point to a defined cache service.

The cache is used for two different operations, one is to provide a caching layer for storing results, and the other one is that Cache is a requirement if you wish to use the Rate Control mechanism.

Security

Security section provides a layer for authorization and authentication above your REST APIs. It is dependent upon the Security component.

The configuration takes two parameters:

If the user doesn't have access, a 403 - Forbidden response is returned.

RateControl

Rate control is a protection mechanism preventing anyone from abusing your REST API in a way the he is making too many requests in a short period of time.

With rate control you set the following parameters:

If limit is reached, and penalty is activated, the component will return 429 - Too Many Requests response, until the limit is restored.

Note that the rate control mechanism requires that you have Cache specified on that REST configuration.

Environment

The value of Environment attribute can either be 'production' or 'development'. The difference is that in development mode we constantly rebuild the compiled cache files, we also output special debug response headers, and JSON output uses pretty format.

Middleware

If this parameter is set, it should point to your class that implements MiddlewareInterface. This gives you control over execution of your REST service method. Everything until and after the execution of the service is done by the component. The component passes the RequestBag to your middleware, and it is up to you how you will execute the method, maybe perform additional checks, or some custom business logic. Whatever you do, the return value will be passed directly to the REST component and will be used as a service result.

Class and method annotations

Annotations are a way of describing certain properties of an object. With annotations you can configure the behaviour of your service. All the REST component annotations have a rest namespace.

All the annotations can be defined on a class level, making them default to methods, and on the method level you can overwrite them. There are no required annotations.

When one class extends another, where the child class is actually your REST API, the parent class automatically passes, its class and method, annotations the child class, so make sure when overwriting methods, that you also overwrite the annotations, if necessary.

The following annotations are available:

@rest.method

Defines over which HTTP method the service can be accessed. If not defined, get is set as default. The supported request types are GET, POST, PUT, PATCH and DELETE. They are not case sensitive.

@rest.default

Defines that this method is the default method for the defined @rest.method request type. For example if you have @rest.method set to post and the method is marked with @rest.default and you do a POST request just to the service name, without the method, the defined default method for POST request will be triggered.

@rest.ignore

This flag tells to the component that it should ignore that method and that it's not part of the service. Usually used for some internal methods.

@rest.cache.ttl

Marks that the returned result from this method can be cached for the specific amount of time. The time is defined in seconds. Note that this feature requires that you have a Cache service defined in your configuration.

@rest.header

There are several options in the header section that you can control:

@rest.role

Defines that a method can only be accessed by users that have the specific, or higher, access level.

This annotation requires that you define the Security section in your configuration.

@rest.rateControl.ignore

This flag marks that rate control will not be applied to that method.

@rest.url

This annotation provides the resource naming feature by specifying a custom url that will be used in the url matching, instead of the method name. Note: When using resource naming, you cannot use @rest.default annotation on that method, and also you cannot specify optional parameters.

Routing and accessing the APIs

This is an example Router config.

The config takes the following parameters:

Class

This parameter tells to the Router how it should implement the matching parameters from the url and the Path to get the class name used for the called Rest service.

Path

Path is a url pattern that the component tries to match agains the current url. If a match is made, the matched parameters are used to create the Class name. All the patterns are inside curly brackets {foo} and ([\w-]+) regex pattern is used for matching.

Normalize

This is an optional feature. It tells to the component if the matched parameters should be normalized. In this case under "normalize" we consider transforming parameter value like this one some-application into this SomeApplication.

Example

Let's say you have the upper configuration example in place. The following url will produce the example class name.

Url: http://www.hats.com/services/my-app/some-longer-name/test/pac-man

Class: \Foo\Bar\MyServices\SomeLongerName\PacMan

Some pre-requirements

All you need to do is set on your web server that all requests should be routed to a single file, for example rest.php On that file call the static iniRest method with the API name. That method returns a new Rest instance where you can call the processRequest method that triggers the service call. If the url is not matched boolean false is returned.

Interfaces

The component provides several interfaces that you can implement on your API class to gain more control over some aspects of the component.

All the interfaces are under the a namespace Webiny\Component\Rest\Interfaces\.

Versioning and VersionInterface

The component gives you the option to version your APIs, meaning that you can have multiple active version of one API. This helps a lot when you are deploying a new version, but you still need to support the old one.

Also you have two version aliases, making things even more simpler for you. The alias is nothing but a pointer to an actual version. The two available aliases are latest and current. If somebody requests your API, and if he hasn't defined a version, he will be pointed to the current version, which is then mapped to an actual version.

In order to implement versioning feature, you need to implement Webiny\Component\Rest\Interfaces\VersionInterface on your class. This looks something like this:

The interface will tell you to implement the upper three methods, getLatestVersion, getCurrentVersion and getAllVersions. The most important method is the getAllVersions which returns an array of supported versions where the key is the version number, in format X.Y, and the class name is the value. This is the class that will be used to handle the requests.

Note that only the 'main' class needs to be registered with the component $rest = new \Webiny\Component\Rest\Rest('InternalApi', 'FooService');. Also the main class is the only one that needs to implement the interface, making everything a whole lot easier to maintain.

How to access a specific version

By default all users will be pointed to the current version. To make a request to a specific version you need to add a request header. The request header name is X-Webiny-Rest-Version and the value is the version. For the version you can send a specific version number, or an alias. All requests that have this header will be mapped to that concrete version.

// point the request to version 2.1

AccessInterface

If you wish to implement your own security layer, you can implement the Webiny\Component\Rest\Interfaces\AccessInterface.

The interface will ask you to define hasAccess method. This method takes only one parameter $role. This parameter contains the value defined in @rest.role annotation. The method should return either true or false, allowing or denying access to the user.

Note that you still need to define the Security section in your REST configuration. The configuration should only contain the default required role. Don't define the Firewall attribute.

ROLE_ANONYMOUS allows non authenticated users to call the service. You can overwrite the required role with the @rest.role annotation on a per-class and per-method basis.

CacheKeyInterface

Rest component, by default, creates cache keys from these parameters:

Implement this interface to define your own method for generating a cache key. Some common use cases are to generate a cache key based on some cookie or token. Note that you should still include the url, query parameters and the http method. Always take into account that generating the cache key doesn't actually take longer than getting the data without cache.

The implementation looks like this:

Note that the returned key is used "as it is", nothing is appended to it, nor it is hashed, so make sure that you return a key with a proper size.

CrudInterface

Implementing this interface you will get the basic CRUD methods and behavior described in the table below:

Request type Url Mapping Description
GET foo-class/ FooClass::crudList Retrieve all records in a collection.
POST foo-class/ FooClass::crudCreate() Create new record.
DELETE foo-class/{id} FooClass::crudDelete($id) Delete a record with the given id.
GET foo-class/{id} FooClass::crudGet($id) Retrieve a single record.
PUT foo-class/{id} FooClass::crudReplace($id) Replace a single record.
PATCH foo-class/{id} FooClass::crudUpdate($id) Update a single record.

RestTrait

In practice you often need to use things like paging, sorting and similar, which doesn't make since to put as a parameter in your method. The best approach is to use query parameters. The RestTrait provides you with helper functions and suggestions.

In the trait you will find the next methods:

Let's see the returned values if we would look at this url: http://api.example.com/my-service/get-pages/?_page=1&_perPage=10&_sort=+Title&_fields=id,title,author,slug

The returned values would be as following:

Return values

The component returns a JSON response, like the one below:

Your result is always encapsulated within the data property.

In case of an error, the data property is omitted, and you will get a response containing errors, like this one:

You can also add additional error entries:

Throwing errors

When you need to throw an error, the best way is using the RestErrorException class.

Debugging

The component will return additional debug information in the response header and in the debug part of the response body. The additional headers are as following:

Here is typical example output:

Compiler cache

The component reads the api classes and creates an array that contains different information about the api services contained within that class. Based on the component environment, that array will be saved. If the environment is development the cached array will be stored in memory inside a static array. If the environment is production the array will be written to the disk, using the CompilePath.

If you wish to create your own compiler cache class, and write, for example to a Redis database, you just need to create a class and implement \Webiny\Component\Rest\Compiler\CacheDrivers\CacheDriverInterface and define the path to the class inside your Rest component config, like this:

Resources

To run unit tests, you need to use the following command:

$ cd path/to/Webiny/Component/Rest/
$ composer.phar install
$ phpunit

Make sure that you update the configuration files inside Test/Mocks/ folder.


All versions of rest with dependencies

PHP Build Version
Package Version
Requires php Version ^7
webiny/std-lib Version ~1.6
webiny/cache Version ~1.6
webiny/config Version ~1.6
webiny/http Version ~1.6
webiny/security Version ~1.6
webiny/annotations Version ~1.6
webiny/router Version ~1.6
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package webiny/rest contains the following files

Loading the files please wait ....