Sei sulla pagina 1di 7

CodeIgniter RAP

Simple RESTful API boilerplate for the CodeIgniter framework.

composer create-project chalarangelo/codeigniter-rap

Introduction
The CodeIgniter RESTful API is a set of simple, modular helpers that can be easily
integrated into your CodeIgniter projects, allowing you to create customizable
RESTful APIs that suit all your needs. The package includes helpers for database
manipulation, JSON Web Token generation, validation and signing, authentication
methods, methods for accessing resources using a URI, as well as some utility
methods that will help streamline your workflow.

Requirements
 PHP: 5.3.7 or greater
 CodeIgniter: 3.1.5 or greater

Installation
1. Copy and paste all the files from application to the corresponding directory in
your application.
2. Copy and paste the config.example.ini file outside your application folder
or create yours, based on the example provided. Remember to name your file
config.ini or rename the sample provided.
3. Create your own secret key and update config.ini to be completely secure.
4. (Optional) Copy and paste the .example.htaccess file and tweak it to your
liking. Remember to rename it to .htaccess.
5. (Recommended) Enable HTTPS for your server for maximum security.

Contents
The API is made up of a set of helpers, each one serving a different purpose. Click on
each helper below to read about its functionality.

 error_code
 request
 database
 jwt
 auth
 rest_api

error_code

Contains values for various error codes. The codes are mostly matched to HTTP
status codes, but some of them might not be perfect matches. The error codes are
stored as global variables.

Variable Value Description


PROHIBITED 405 The action is not allowed.
The data is malfored or does not match expected
BAD_DATA 400
input.
The credentials provided cannot be successfully
BAD_CREDENTIALS 403
authorized.
The user has not the proper authorization to perform
UNAUTHORIZED 403
this action.
NO_COOKIE 409 The expected cookie was not found.
SUCCESS 200 The action was successful.

request

Contains a single method for retrieving the body of the current request.

 get_request_body(): Retrieves the body of the current request.


o returns the body of the current request

database

Contains multiple methods for connecting and retrieving information from the
database.

 database_connect(): Establishes a connection to the database. The


connection's parameters (host, username, password and database name) are
parsed from the config.ini file, residing in the CodeIgniter root folder.
o returns a connection to the database
 database_query($query, $types, $params, $query_type): Uses a
prepared statement to query the database, returning an associative array or
false, based on the query's results.
o $query: The query to the database, as a string.
o $types: A string that contains one or more characters which specify
the types for the corresponding bind variables.
o $params: An array of values that will be passed as parameters to the
query. The types of the parameters must match the types specified by
$types.
o $query_type: (Optional) The type of query that will be executed
("SELECT" (default), "INSERT", "UPDATE", "DELETE"). The
execution of the prepared statement will return different kinds of
results based on the type specified.
o returns an associative array or false
 database_no_args_query($query):
o Queries the database, returning an associative array or false, based on
the query's results. The query must have no arguments (e.g. useful for
retrieving all values from a table).
o $query: The query to the database, as a string.
o returns an associative array or false
 database_error(): Returns the last connection error, if any.
o returns error description

jwt

Heavily based on this implementation, the JWT helper allows for the creation of
JSON Web Tokens. The secret key provided in config.ini will be used to sign the
token.

 jwt_encode($payload, $key, $algo): Creates a JWT string.


o $payload: The payload of the JSON Web Token.
o $key: The secret key
o $algo: (Optional) The signing algorithm ('HS256' (default), 'HS384'
or 'HS512').
o returns a signed JWT
 jwt_decode($jwt, $key, $verify): Decodes a JWT string.
o $jwt: The JSON Web Token.
o $key: The secret key.
o $verify: (Optional) Toggles verification of token on/off.
o returns the payload of the JWT
 sign($msg, $key, $method): Signs a string with a given key and algorithm.
o $msg: The message to sign.
o $key: The secret key.
o $algo: (Optional) The signing algorithm ('HS256' (default), 'HS384'
or 'HS512').
o returns encrypted message
 json_e_encode($input): Encodes into a JSON string (with error handling).
o $input: Object to be encoded.
o returns the JSON representation of the object
 json_e_decode($input): Decodes a JSON string (with error handling).)
o $input: JSON string to be decoded.
o returns the object representation of the JSON string
 urlsafe_base64_encode($input): Encodes a string with URL-safe Base64.
o $input: A string to be encoded.
o returns the Base64 encoded string
 urlsafe_base64_decode($input): Decodes a string with URL-safe Base64.
o $input: A Base64 string to be decoded.
o returns a decoded string

auth

Contains multiple methods used for authorization, authorization validation and usage
with JSON Web Tokens in cookies.

 authorize($table, $fields, $username_field, $password_field,


$id_field, $username_value, $password_value, $service_name,
$cookie_name): Provides authorized access to the system for a user, based on
the provided credentials, using a query to the database. If the authorization is
successful, a unique JSON Web Token is generated and stored in a cookie.
o $table: The database table to query.
o $fields: An array of names for the fields to be requested.
o $username_field: The name of the username field.
o $password_field: The name of the password field.
o $id_field: The name of the id field.
o $username_value: The value of the username field.
o $password_value: The value of the password field.
o $service_name: The name of the service.
o $cookie_name: The name of the cookie used to store the authorization
token.
o returns an associative array
 generate_jwt_cookie($username_value, $id_value, $service_name,
$cookie_name): Generates a unique JSON Web Token from the values
provided.
o $username_value: The user's unique username.
o $id_value: The user's unique id.
o $service_name: The name of the service.
o $cookie_name: The name of the cookie used to store the authorization
token.
o returns void
 regenerate_jwt_cookie($service_name, $cookie_name): Regenerates a
unique JSON Web Token from the values provided. Will return a message if
no existing cookie is found.
o $service_name: The name of the service.
o $cookie_name: The name of the cookie used to store the authorization
token.
o returns an associative array
 check_jwt_cookie($service_name, $cookie_name): Checks the validity
of a unique JSON Web Token.
o $service_name: The name of the service.
o $cookie_name: The name of the cookie used to store the authorization
token.
o returns true if the cookie is found and the JWT is valid, false
otherwise
 get_jwt_data($cookie_name): Gets the data stored in a unique JSON Web
Token.
o $cookie_name: The name of the cookie used to store the authorization
token.
o returns an associative array

rest-api

Contains multiple methods, implementing generic CRUD methods for a RESTful


API. For security reasons, certain methods are not implemented, but rather return an
associative array with an error code and a message.

 createResourceRoot(): Creates a new collection, using a query to the


database.
o returns an associative array with an error message
 createResourceElement($table, $input_fields, $input_types,
$input_values): Creates a new entry in a collection, using a query to the
database.
o $table: The database table to query.
o $input_fields: An array of names for the fields to be filled.
o $input_types: A string that contains one or more characters
o which specify the types for the corresponding fields.
o $input_values: An array of values for the fields to be filled.
o returns the id of the newly-created collection member
 readResourceRoot($table, $fields): Lists the members of a collection,
using a query to the database.
o $table: The database table to query.
o $fields: The table's fields to be retrieved.
o returns a collection of elements
 readResourceElement($table, $fields, $element_key, $key_value):
Retrieves a specific member of a collection, using a query to the database.
o $table: The database table to query.
o $fields: The table's fields to be retrieved.
o $element_key: The table's field that will be used for the specific
o resource's indentification.
o $key_value: The value to be used for the specific resource's
o identification.
o returns a list of members or false
 updateResourceRoot(): Updates a resource collection, using a query to the
database.
o returns an associative array with an error message
 updateResourceElement($table, $input_fields, $input_types,
$input_values, $element_key, $key_value): Updates a specific member
of a collection, using a query to the database.
o $table: The database table to query.
o $input_fields: An array of names for the fields to be updated.
o $input_types: A string that contains one or more characters
o which specify the types for the corresponding fields.
o $input_values: An array of values for the fields to be updated.
o $element_key: The table's field that will be used for the specific
o resource's indentification.
o $key_value: The value to be used for the specific resource's
o identification.
o returns the number of affected rows
 deleteResourceRoot(): Deletes a resource collection, using a query to the
database.
o returns an associative array with an error message
 deleteResourceElement($table, $element_key, $key_value): Deletes
a specific member of a collection, using a query to the database.
o $table: The database table to query.
o $element_key: The table's field that will be used for the specific
o resource's indentification.
o $key_value: The value to be used for the specific resource's
o identification.
o returns the number of affected rows
How to use
The provided helpers are supposed to be used in a CI_Controller, but you can use
them any way you like. The sample provided (controllers/Api.php) is a pretty good
starting point for a RESTful API implementation:

 All helpers are loaded in the __construct() method of the Api class. Certain
variables are also instantiated to be used for the API's requests.
 The index() method is an empty method returning an error message, when
no resource is specified in the request in the form of a URI.
 The users($param) method maps the different API methods to HTTP
methods (CREATE = POST, READ = GET, UPDATE = PUT, DELETE =
DELETE) and uses the various helpers and class variables to provide a sample
RESTful API implementation.
 The login($param) method allows for the authorization of a user (needed to
update or delete a resource matched to his/her username).

To query the API, you should use something like


example.com/index.php/api/resource_name (or
example.com/api/resource_name, if you are using the .htaccess file provided,
configured to your environment), replacing resource_name with your resource's
name (e.g. users). Bear in mind that certain requests will return errors due to
implementation specifics.

License
The project is licensed under the MIT license.

Potrebbero piacerti anche