Introduction Last updated : 2020-07-12

Official documentation

API Provider is a PHP APIs framework that generates automatically CRUD operations links using database tables's models, the API Provider works with routing using context and actions from url request. Moreover, this provider protects your data, you can specify for each model(table) the privileges that users can access.
Beside the CRUD operations, it offers you preferred models contexts that you can create to handle complex requests such as joined models, aggregations and so on ...

Installation

Installing API Provider is much easier that making a birthday cake, just follow the instructions bellow to install it in localhost or even a web hosting service.

Localhost

To install and run API Provider on localhost, you have to add php.exe file path to the environment variable PATH then follow these steps.

  • Copy the project folder (apiprovider) to the your web server folder (www, htdocs ...)
  • Enter to command line (CMD) and execute this command php provider connection
  • Fill in all connection infos (hostname, username, password and database name)
  • You are all set up :)

No you have all set up, just run your server and start creatings models using the API Provider CLI.

Web hosting

To install API Provider in a web hosting service, you have to upload the project folder (apiprovider) to your CPanel's file manager in the public_html folder then configure the api as shown in the 3 steps mentioned above.
After that you have to create models, privileges and preferred models manually, so first :

  • create 3 folders under the apiprovider folder (models, preferred and privileges)
  • Refer to API Provider CLI section to create a CRUD model or a preferred model.

CRUD Operations

This API Provider comes with a built-in CRUD url that reduces you efforts to about 60%

Introduction

Most of the time, when you want to use an API to access the database from a mobile app, you have to create a lot of CRUD operations links to manipulate the data of a specific table in the database, this is why API Provider comes to help, it generates automatically those links, you can disable the access to a specific privilege in a model using API Provider CLI.

CRUD Operations

The valid CRUD actions that are built with API Provider are :

  • findall : give you the possibility to fetch all rows from a table
  • find&[column=?&...] : retrieve rows where a condition
  • delete&column=? : delete rows where a condition
  • insert&[column=?&...] : inserts a row with given fields
  • update&condition=?&[column=?&...] : updates a row's fields with given condition
Ps: For the update link the first param after action MUST be the conditional row such us ID then followed by other fields

Aggregations

  • count : counts total rows
  • count&[column=?&...] : counts rows where a condition

Examples

Using devcrawlers.com as a hostname

  • Select all products : https://devcrawlers.com/api/index.php?context=product&action=findall
  • Select a product with ID 7 : https://devcrawlers.com/api/index.php?context=product&action=find&id_pro=7
  • Select all products cost 100$ : https://devcrawlers.com/api/index.php?context=product&action=find&price=100
  • Delete a product : https://devcrawlers.com/api/index.php?context=product&action=delete&id_pro=2
  • Count products : https://devcrawlers.com/api/index.php?context=product&action=count
  • Count products cost 100$ : https://devcrawlers.com/api/index.php?context=product&action=count&price=100
  • Update a product with ID 7 : https://devcrawlers.com/api/index.php?context=product&action=update&id=7&price=160
  • Insert a new product : https://devcrawlers.com/api/index.php?context=product&action=insert&name=toto&price=100

Preferred Models

The preferred handlers gives you the possibility to perform complex queries with a single line of code

Introduction

Sometime you want to request complex requests such as tables joining and complex aggregations, this is what you can do with preferred models, you can write your own queries, you have just to specify cases for the context action and start writing your lines.

Usage

Use the provider command line (php provider create_preferred) to generate a custom handler then implement handle function using cases from given action. Creating a query to retrieve all products and their categories, here is how the file must look like
Now that you are able to create a preferred model, lets discover what it offers you :

  • $this->getAction() : retrieves the action provided in the link
  • $this->getParams() : returns all parameters passed in the link
  • $this->getDirectory() : returns the current working directory (default is preferred)
  • $this->getDracula() : return Dracula object to perform MySQL requests (query() & queryUpdate())
  • $this->getContext() : return current context (the name of preferred model)
  • $this->getMethod() : return request method (GET or POST)
  • $this->getInput() : returns php input received from request body

Example

getAction()){

			case 'find':
				(new Logger())->json((new Dracula())->query("SELECT * FROM product NATURAL JOIN category"));
				break;

		}
	}

}

?>

by accessing the 'find' action you will get the json response.
https://devcrawlers.com/api/index.php?context=mypreferredmodel&action=find

Binder

The Binder container helps you to created aggregated joins between tables in json format, imagine we want to have an output of all categories in our store, and each category must have a list of products, to do so, the Binder would help you to acheive that kind of requests smoothely

To use the Binder, created a Preffered Handler then add a new action case and use the Binder as follow :

getAction()){

			case 'stock':
				(new Binder('categorie'))
				->hasMany('produit')
				->criteria(['id_category'])
				->handle()->json();
			break;

		}
	}

}

You can also add a ->where(['id_category'], [8]) before ->handle() to retreive just the category with ID 8 and its products

Example of returned json object

[
    {
        "id": 8,
        "nom": "Accessories",
        "desc": "All computer and phone accessories",
        "products": [
            {
                "id": 645,
                "ref": "R7000",
                "nom": "JBL headphones for gamers",
                "qtt": 0,
                "cost_price": 0,
                "price": 30,
                "picture": "images/products/nM5nX0ghS0xb3S6W0rGSB2.jpg",
                "id_cat": 8
            },
            {
                "id": 845,
                "ref": "R7002",
                "nom": "Mouse Rizer X11 3000dpi",
                "qtt": 0,
                "cost_price": 74,
                "price": 74.1,
                "picture": "images/products/N9518q4e8CAxEpE2VpXJsg.jpg",
                "id_cat": 8
            }
        ]
    }
]

WebGet

This context gives you the possibility to fetch a url and retrieve its source code.

Introduction

The most common problem face when you want to fetch a web page on the net is CORS, which requires the presence of the Access-Control-Allow-Origin header from the server, the WebGet works here as a middleware, when you try to fetch a page, it uses backend techs (curl) to get the url content then returns the result for you without any requirements.

Usage

To use this context follow the following link structure : hostname/project_name/?context=webget&url=?

Example

Get the source code of DevCrawlers home page :
hostname/project_name/?context=webget&url=https://devcrawlers.com

JS & Android Fetch

You can use this code with Javascript frameworks too such as ReactJS, VueJS, React Native, Angular ...

Using GET method

This options is the best way to retrieve find and findall actions

fetch(url_to_api_provider)
.then(response => response.json())
.then(data => {
	// data contains you json response
})
.catch(err => console.log(err))
	

Using POST method

To ensure that your sensitive data are transferred securely for insert, update and delete actions use POST request

fetch(url_to_api_provider,
	{
	method: "POST",
	headers: {
		'Accept': 'application/json, text/plain, */*',
		"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
	},
		body: "context=produit&action=insert&id=1137&name=Product2&price=160",
	}
)
.then(response => response.json())
.then(data => {
	// data contains you json response
})
.catch(err => console.log(err))

Using API Consumer with Java, Android & Kotlin

Usage

The API Consumer is a tool developed by Armane (a software engineer and code lover), its a tool that can consumer the API Provider perfectly in Java based applications.
To use the API Consumer visit JitPack and follow the instructions.

Examples

Using API Consumer with GET requests

This code snippet will retreive all products from products table

JsonRequest jrequest = new JsonRequest("https://devcrawlers.com/apiprovider/")
	.onFinish(response -> System.out.println(response))
	.onError(ex -> ex.printStackTrace())
	.addParams(new String[][]{
			{"context", "products"},
			{"action", "findAll"},
	});
jrequest.doGet();

Saving data using POST method

To push data to server, use the following code

JsonRequest jrequest = new JsonRequest("https://devcrawlers.com/apiprovider/")
	.onFinish(response -> System.out.println(response))
	.onError(ex -> ex.printStackTrace())
	.addParams(new String[][]{
			{"context", "products"},
			{"action", "findAll"},
	});
jrequest.doPost();

The addParams(String[][]|Map) can take a array of objects or you can simply pass an existing HashMap as parametters

Map myparams = new HashMap();
myparams.put("context", "products");
myparams.put("action", "count");

JsonRequest jrequest = new JsonRequest("https://devcrawlers.com/apiprovider/")
	.onFinish(response -> System.out.println(response))
	.onError(ex -> ex.printStackTrace())
	.addParams(myparams);
jrequest.doGet();

Using Kotlin

var req = JsonRequest("https://devcrawlers.com/apiprovider/")
req.onFinish { jsonResponse -> Log.d("result", jsonResponse.jsonObject.toString()) }
	.onError { exception -> exception.printStackTrace() }
	.addParams(arrayOf(
		arrayOf("key", "val"),
		arrayOf("key2", "val2")
	))
	.doGet()

Many thanks to Abderrahmane Arache for creating this great tool :)

Features

Beside the previously discussed functionnalities, API Provider offers you more much feauture to simplify user tasks.

API Provider CLI

This file helps you to create models easily without writing a single line of code, that helps also to build a well formed model that should not have problems during the api process.

Usage

To use this file, enter to command line and switch to project directory then execute php provider [OPTION [VALUE]] Valid options are :

  • create_model Modelname : This one creates a model with the given name
  • create_preferred Modelname : Create a preferred model under preferred directory
  • clear : This command deletes all models in project (critical usage)
  • grant : Used to give a model the permission to select, update, insert, delete or all
  • You can grant post to tell the provider to not accept insert, delete and update operations with GET method, the user will get a message error 'You have to use POST method instead'
  • revoke : Used to delete model's permissions
  • update : Update the API Provider to a higher version is exists (not available yet)
Example of use : php provider create_model Product
This will ask you fields of the model, the fields names MUST be the same in the database table, if you are done with fields then just let the next one empty and press ENTER to finish the process and you will get you model ready to be used.

To create a model manually, create a file with the model name with first letter capital inside the models folder (ex : Product.php) then insert the following code structure depending on your model columns


To create a preferred model manually, copy this example and paste it in a file inside preferred folder with a name for the model (first letter in capital letter ex Mypreferred.php).

Auto-updater

To update your API Provider dependencies to the latest version, use the batch file updater.bat just double click and wait for the update process to be done.
The updater requires Git installed in your computer, if you don't have it, get it from Git SCM.

Tokener

The tokener feature is a simple jwt-like engine to secure the access to your api routes, when you use this feature, just the authenticated users can access your database and interact with it.

To activate this feature just execute the following command : php provider require tokener [table_name], where the [table_name] is the name of the table you use to store users in your application ex: users.
This will create a file named tokener.config in the root directory and a preffered model named Authentication.php inside preferred folder.

The file tokener.config contains two main configurations, the table name and tokener state which accepts true or false (false by default).
To activate tokener execute the following : php provider tokener up.
To shutdown tokener execute the command : php provider tokener down

table=users
active=false

If you did now migrate the tokener to database you will face some errors in your response, to migrate the fields of tokener execute php provider tokener migrate this will create two field in you users table (token and token_expires) which holds the token and the timestamp when the token expires (30days after authentication), to delete the created fields execute php provider tokener rollback.


you need to edit the username/email field name and password field name in preferred/Authentication.php file, you can even specify if you are using an md5 encryption for the passsword by setting $use_md5_encryption to false or just text plain (default). The $register_fields is a list of fields that you want to fill while registring new account like fullname, phone address ...


Note
You have to add token and token_expires variable in your users model file models/[users_model_name].php as following :

How to use Tokener

After configurating tokener with the steps above, you will be able to use it as follow :

  • use the route hostname/project_name/?context=authentication&action=login to log in to an account, this will return user information with token
  • use the route hostname/project_name/?context=authentication&action=register to create new account, this will return created user information with token
  • to execute any other routes use hostname/project_name/?context=context_name&action=action_name&token=token_value
  • to destroy token by logging out execute hostname/project_name/?context=authentication&action=logout&token=token_value

FAQs

Here you find the most asked questions about the API Provider, if you have any other problem please raise a issue on github repository.

Installation

An error with httpUrlConnection in java #1

Yes, the porblem was in the way we was retreiving data from the request, we have fixed this problem in the current version, please update you API Provider dependencies via updater.bat or clone the master version.

Preferred

Question

Answer

Tokener

Getting mysqli errors when trying to access with token

Please try to configure you tokener by following these steps :

  • php provider require tokener
  • php provider tokener migrate
  • php provider tokener up
  • add var $token; and var $token_expires; in your users model inside models folder
  • edit username/email and password fields name and define wheather to use md5 ecryption for password or not in preferred/Authentication.php

Documentation by DevCrawlers 2020 ©, All rights reserved to Crawlers Open Source