All Projects → octobroid → oc-api-plugin

octobroid / oc-api-plugin

Licence: MIT license
Base API Plugin for OctoberCMS

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to oc-api-plugin

liqe
Lightweight and performant Lucene-like parser, serializer and search engine.
Stars: ✭ 513 (+1873.08%)
Mutual labels:  serializer
drf-action-serializer
A serializer for the Django Rest Framework that supports per-action serialization of fields.
Stars: ✭ 48 (+84.62%)
Mutual labels:  serializer
ikeapack
Compact data serializer/packer written in Go, intended to produce a cross-language usable format.
Stars: ✭ 18 (-30.77%)
Mutual labels:  serializer
oc-api-plugin
Tools for building RESTful HTTP + JSON APIs for OctoberCMS.
Stars: ✭ 28 (+7.69%)
Mutual labels:  octobercms
util
封装了一些Java常用的功能
Stars: ✭ 19 (-26.92%)
Mutual labels:  serializer
ta-json
Type-aware JSON serializer/parser
Stars: ✭ 67 (+157.69%)
Mutual labels:  serializer
vdf-parser
📜 Libraries to (de)serialize Valve's KeyValue format (VDF) in various languages
Stars: ✭ 70 (+169.23%)
Mutual labels:  serializer
SaveManager
A simple, yet powerful binary serializer for persisting game data in Unity.
Stars: ✭ 36 (+38.46%)
Mutual labels:  serializer
jest-serializer-html-string
A better Jest snapshot serializer for plain html strings
Stars: ✭ 17 (-34.62%)
Mutual labels:  serializer
oc-mall-theme
Demo theme for the oc-mall-plugin
Stars: ✭ 19 (-26.92%)
Mutual labels:  octobercms
Apex.Serialization
High performance contract-less binary serializer for .NET
Stars: ✭ 82 (+215.38%)
Mutual labels:  serializer
rtsp-types
RTSP (RFC 7826) types and parsers/serializers
Stars: ✭ 16 (-38.46%)
Mutual labels:  serializer
django-serializable-model
Django classes to make your models, managers, and querysets serializable, with built-in support for related objects in ~150 LoC
Stars: ✭ 15 (-42.31%)
Mutual labels:  serializer
php-json-api
JSON API transformer outputting valid (PSR-7) API Responses.
Stars: ✭ 68 (+161.54%)
Mutual labels:  serializer
debugbar-plugin
Integrates PHP Debugbar with October CMS
Stars: ✭ 36 (+38.46%)
Mutual labels:  octobercms
LVDS-7-to-1-Serializer
An Verilog implementation of 7-to-1 LVDS Serializer. Which can be used for comunicating FPGAs with LVDS TFT Screens.
Stars: ✭ 33 (+26.92%)
Mutual labels:  serializer
Bois
Salar.Bois is a compact, fast and powerful binary serializer for .NET Framework. With Bois you can serialize your existing objects with almost no change.
Stars: ✭ 53 (+103.85%)
Mutual labels:  serializer
JsonFormatter
Easy, Fast and Lightweight Json Formatter. (Serializer and Deserializer)
Stars: ✭ 26 (+0%)
Mutual labels:  serializer
Docktober
🍂 Simple: Docker + OctoberCMS
Stars: ✭ 57 (+119.23%)
Mutual labels:  octobercms
typeserializer
🎉 Awesome serializer / deserializer for javascript objects
Stars: ✭ 94 (+261.54%)
Mutual labels:  serializer

API Framework for OctoberCMS

It's a plugin for OctoberCMS for you that want to create an extensible and easy to use API server.

Features

Installation

  1. Download this plugin and put to plugins directory (plugins/octobro/api).
  2. Run composer update on your project root directory.

Tips: if you want to follow this plugin, you can use this plugin as a submodule on your git project.

Usage

This plugin is a base for your application API. You should create your "API" plugin for your application.

Create Your Plugin

php artisan create:plugin Foo.Bar

In your Plugin.php file, we recommend you to put Octobro.API as plugin dependency.

class Plugin extends PluginBase
{
	public $require = ['Octobro.API'];
	

Define the REST API Routes

Create routes.php using this starter template.

Route::group([
	'prefix'     => 'api/v1',
	'namespace'  => 'Foo\Bar\ApiControllers',
	'middleware' => 'cors'
], function() {
	
	//	
	// Your public resources should be here
	//
	
});

Don't forget to change the Controllers namespace on your plugin.

Create Your App Resources

For example in an e-commerce application, we want to open the products catalog API.

Put the URL to your plugins/foo/bar/routes.php

Route::get('products', 'Products@index');
Route::get('products/{id}', 'Products@show');

Route::post('orders', 'Orders@store');

Create the plugins/foo/bar/apicontrollers/Products.php file.

<?php namespace Foo\Bar\ApiControllers;

use Octobro\API\Classes\ApiController;
use Foo\Bar\Models\Product;
use Foo\Bar\Transformers\ProductTransformer;

class Products extends ApiController
{
    public function index()
    {
        $products = Product::get();

        return $this->respondwithCollection($products, new ProductTransformer);
    }

    public function show($id)
    {
    	$product = Product::find($id);

    	return $this->respondwithItem($product, new ProductTransformer);
    }
}

Create The Transformers

Transformer will help you to transform data from a model object to set of array including relationship using include and exclude query.

For example in this case, we create the plugins/foo/bar/transformers/ProductTransformer.php

<?php namespace Foo\Bar\Transformers;

use Octobro\API\Classes\Transformer;
use Foo\Bar\Models\Product;

class ProductTransformer extends Transformer
{
    // Related transformer that can be included
    public $availableIncludes = [
    	'categories',
    	'brand',
    ];
    
    // Related transformer that will be included by default
    public $defaultIncludes = [
    	'categories',
    ];

    public function data(Product $product)
    {
        return [
            'id'          => (int) $product->id,
            'sku'         => $product->sku,
            'name'        => $product->name,
            'description' => $product->description,
            'price'       => $product->price,
            'sale_price'  => $product->sale_price,
            'image'       => $this->image($product->image),
            'gallery'     => $this->images($product->gallery),
            'created_at'  => date($product->created_at),
        ];
    }
    
    public function includeCategories(Product $product)
    {
        return $this->collection($product->categories, new CategoryTransformer);
    }
    
    public function includeBrand(Product $product)
    {
        return $this->item($product->brand, new BrandTransformer);
    }
}

With Scaffolding Command

You can also create a transformer using the scaffolding commands to speed up your development process.

Use octobro:transformer command to create a new transformer. The first parameter specifies the author and plugin name. The second parameter specifies the model name. Note that the model name must be written with its namespace and the backward slash used must be doubled.

php artisan octobro:transformer Foo.Bar Foo\\Bar\\Models\\Product

That's it! You're successfully created the API in easy way! There are ton of features that very usable for your scalable and extensible application.

Trying the API

We recommend you to use API client like Postman or Insomnia for easy testing.

Basic Call

GET http://example.com/api/v1/products

The response will be.

{
    "data": [
        {
            "id": 1,
            "name": "Sample Prouct",
            ...
        },
        ...
    ]
}

Using Include Query

GET http://example.com/api/v1/products?include=brand,categories

{
    "data": [
        {
            "id": 1,
            "name": "Sample Prouct",

            "brand": {
                "data": {
                    "id": 21,
                    "name": "Nike",
                    ...
                }
            },

            "categories: {
                "data": [
                    {
                        "id": 45,
                        "name": "Hot Product",
                        ...
                    },
                    {
                        "id": 8,
                        "name": "Shoes",
                        ...
                    }
                ]
            }
        }
    ]
}

Using Paginator

GET http://example.com/api/v1/products?page=2,number=20

{
    "data": [
        {
            "id": 1,
            "name": "Sample Prouct",
            ...
        },
        ...
    ],
    "meta": {
        "pagination": {
            "total": 1,
            "count": 1,
            "per_page": 20,
            "current_page": 2,
            "total_pages": 10,
            "links": {
                "previous": "http://example.com/api/v1/products?page=1",
                "next": "http://example.com/api/v1/products?page=3"
            }
        }
    }
}

Configuring Serializer

By default this plugin is using DataArraySerializer from Fractal. If you want to use another serializer, there are another options like ArraySerializer or JsonApiSerializer.

To change the serializer you can extend it on your own Plugin.php.

use Octobro\API\Classes\ApiController;
use League\Fractal\Serializer\JsonApiSerializer;

class Plugin extends PluginBase
{
    public $require = ['Octobro.API'];

    public function boot()
    {
    	ApiController::extend(function($controller) {
    		$controller->fractal->setSerializer(new JsonApiSerializer());
    	});
    }
}

Recommended Plugins

We are building another API-enabled plugins that can be used easily!

Extending Plugins

Need to extend the plugin? We can just add some lines to add the fields of data, or even creating or manipulating includes query.

In this example we want to extend ProductTransformer.php.

Adding Fields

// Add this on your plugin boot() method

ProductTransformer::extend(function($transformer) {

    // Add field one by one
    $transformer->addField('tags', function($product) {
        return $product->tags->toArray();
    });
    
    // Add field based on object attribute
    // In this case, if the Product has tax attribute ($product->tax)
    $transformer->addField('tax');
    
    // Wanna add more fields based on attributes?
    // You can put it all together
    $transformer->addFields(['url', 'color', 'is_recommended']);
});

Adding Includes

// Add this on your plugin boot() method

ProductTransformer::extend(function($transformer) {

    // For example it has reviews relation
    $transformer->addInclude('reviews', function($product) use ($transfomer) {
        return $transformer->collection($product->reviews, new ReviewTransfomer);
    });
    
    // Or if it has single relation
    $transformer->addInclude('brand', function($product) use ($transfomer) {
        return $transformer->item($product->brand, new BrandTransformer);
    });    
});

Composer Packages Used

License

The OctoberCMS platform is open-sourced software licensed under the MIT license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].