Giter Club home page Giter Club logo

arrestdb's Introduction

#ArrestDB

ArrestDB is a "plug-n-play" RESTful API for SQLite, MySQL and PostgreSQL databases.

ArrestDB provides a REST API that maps directly to your database stucture with no configuation.

Lets suppose you have set up ArrestDB at http://api.example.com/ and that your database has a table named customers. To get a list of all the customers in the table you would simply need to do:

GET http://api.example.com/customers/

As a response, you would get a JSON formatted list of customers.

Or, if you only want to get one customer, then you would append the customer id to the URL:

GET http://api.example.com/customers/123/

##Requirements

  • PHP 5.4+ & PDO
  • SQLite / MySQL / PostgreSQL

##Installation

Edit index.php and change the $dsn variable located at the top, here are some examples:

  • SQLite: $dsn = 'sqlite://./path/to/database.sqlite';
  • MySQL: $dsn = 'mysql://[user[:pass]@]host[:port]/db/;
  • PostgreSQL: $dsn = 'pgsql://[user[:pass]@]host[:port]/db/;

If you want to restrict access to allow only specific IP addresses, add them to the $clients array:

$clients = array
(
	'127.0.0.1',
	'127.0.0.2',
	'127.0.0.3',
);

After you're done editing the file, place it in a public directory (feel free to change the filename).

If you're using Apache, you can use the following mod_rewrite rules in a .htaccess file:

<IfModule mod_rewrite.c>
	RewriteEngine	On
	RewriteCond		%{REQUEST_FILENAME}	!-d
	RewriteCond		%{REQUEST_FILENAME}	!-f
	RewriteRule		^(.*)$ index.php/$1	[L,QSA]
</IfModule>

Nota bene: You must access the file directly, including it from another file won't work.

##API Design

The actual API design is very straightforward and follows the design patterns of the majority of APIs.

(C)reate > POST   /table
(R)ead   > GET    /table[/id]
(R)ead   > GET    /table[/column/content]
(U)pdate > PUT    /table/id
(D)elete > DELETE /table/id

To put this into practice below are some example of how you would use the ArrestDB API:

# Get all rows from the "customers" table
GET http://api.example.com/customers/

# Get a single row from the "customers" table (where "123" is the ID)
GET http://api.example.com/customers/123/

# Get all rows from the "customers" table where the "country" field matches "Australia" (`LIKE`)
GET http://api.example.com/customers/country/Australia/

# Get 50 rows from the "customers" table
GET http://api.example.com/customers/?limit=50

# Get 50 rows from the "customers" table ordered by the "date" field
GET http://api.example.com/customers/?limit=50&by=date&order=desc

# Create a new row in the "customers" table where the POST data corresponds to the database fields
POST http://api.example.com/customers/

# Update customer "123" in the "customers" table where the PUT data corresponds to the database fields
PUT http://api.example.com/customers/123/

# Delete customer "123" from the "customers" table
DELETE http://api.example.com/customers/123/

Please note that GET calls accept the following query string variables:

  • by (column to order by)
    • order (order direction: ASC or DESC)
  • limit (LIMIT x SQL clause)
    • offset (OFFSET x SQL clause)

Additionally, POST and PUT requests accept JSON-encoded and/or zlib-compressed payloads.

POST and PUT requests are only able to parse data encoded in application/x-www-form-urlencoded. Support for multipart/form-data payloads will be added in the future.

If your client does not support certain methods, you can use the X-HTTP-Method-Override header:

  • PUT = POST + X-HTTP-Method-Override: PUT
  • DELETE = GET + X-HTTP-Method-Override: DELETE

Alternatively, you can also override the HTTP method by using the _method query string parameter.

Since 1.5.0, it's also possible to atomically INSERT a batch of records by POSTing an array of arrays.

##Responses

All responses are in the JSON format. A GET response from the customers table might look like this:

[
    {
        "id": "114",
        "customerName": "Australian Collectors, Co.",
        "contactLastName": "Ferguson",
        "contactFirstName": "Peter",
        "phone": "123456",
        "addressLine1": "636 St Kilda Road",
        "addressLine2": "Level 3",
        "city": "Melbourne",
        "state": "Victoria",
        "postalCode": "3004",
        "country": "Australia",
        "salesRepEmployeeNumber": "1611",
        "creditLimit": "117300"
    },
    ...
]

Successful POST responses will look like:

{
    "success": {
        "code": 201,
        "status": "Created"
    }
}

Successful PUT and DELETE responses will look like:

{
    "success": {
        "code": 200,
        "status": "OK"
    }
}

Errors are expressed in the format:

{
    "error": {
        "code": 400,
        "status": "Bad Request"
    }
}

The following codes and message are avaiable:

  • 200 OK
  • 201 Created
  • 204 No Content
  • 400 Bad Request
  • 403 Forbidden
  • 404 Not Found
  • 409 Conflict
  • 503 Service Unavailable

Also, if the callback query string is set and is valid, the returned result will be a JSON-P response:

callback(JSON);

Ajax-like requests will be minified, whereas normal browser requests will be human-readable.

##Changelog

  • 1.2.0 support for JSON payloads in POST and PUT (optionally gzipped)
  • 1.3.0 support for JSON-P responses
  • 1.4.0 support for HTTP method overrides using the X-HTTP-Method-Override header
  • 1.5.0 support for bulk inserts in POST
  • 1.6.0 added support for PostgreSQL
  • 1.7.0 fixed PostgreSQL connection bug, other minor improvements
  • 1.8.0 fixed POST / PUT bug introduced in 1.5.0
  • 1.9.0 updated to PHP 5.4 short array syntax

##Credits

ArrestDB is a complete rewrite of Arrest-MySQL with several optimizations and additional features.

##License (MIT)

Copyright (c) 2014 Alix Axel ([email protected]).

arrestdb's People

Contributors

alixaxel avatar bign8 avatar gilbitron avatar lievenjanssen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

arrestdb's Issues

No json data back at postgres request

Hello @alixaxel I guess you take my doubt of please.

i've tested from the oldest to the newest files with you code. And congratulation. It was just what I need! I can connect with mysql perfectly! But when I will connect with postgresql database it returns null :( I tryed to request to get some responses for example not found, bad requests and it was ok! But when I put the correct forms, i've received null! Nothing appears at the GET response.

I've tryied with the new commits from @aweiand here #1 and it changes anythings. My problem is that the json data returning as response, simply cant appears!

Please, Can you help me?!

Best Regards, Atenciosamente,
Rogério Cassares Pires

debug mechanism

trying to understand what is going on..
i guess a lot of the PDO work happens in
457 if ($result[$hash]->execute($data) === true)

could there be a HTTP parameter so we can see (debug mode) what exact query is intended to be executed?

i am trying to hack into this to make it compatible with CouchDB REST and i am not as good at coding as you are..

503 : Service Unavailable

Hello,

Thanks for this amazing fork on ArrestMySQL !
I wanted to try it out with a SQLite3 database but I am still having a error : '503 : Service Unavailable'.

Here is my variable dsn :
$dsn = 'sqlite://./var/www/ratp.db';

I tried every possiblity like :
$dsn = 'sqlite:///var/www/ratp.db';
$dsn = 'sqlite:/var/www/ratp.db';
$dsn = 'slite:ratp.db';

Nothing seems to be working :(

Restangular with ArrestDB

I'm using Restangular together with ArrestDB, how ArrestDB interprets this angular method or does it?

// Just ONE GET to /accounts/123/buildings/456
Restangular.one('accounts', 123).one('buildings', 456).get()

In your documentation you only accept, (R)ead > GET /table[/column/content].

Thanks

Restrict Access by Url or Developer Key

hi.
great project.
I saw that there's a restrict access by ip. I'm working with heroku and its free dynamic ip (every update pushed to heroku restart the server and assigned with a new dynamic ip).

So, i'de like to know if there's a chance to add a restriction by url (or uri) or by a developer key that will be supplied (similar to using a known api like tweeter/youtube/facebook).

thanks.

409 for put / insert

I'm getting 409 when trying to put a new record, or update existing records. Dumping the insert query shows '?'s in the query. Are these not getting replaced later on?

400 - Bad Request

Hi,

I keep getting this "400 - Bad Request" error, in spite of keeping the index.php and test.db in the same folder.

My URL format: http://xyz.net/apps/ArrestDB/std

  • Where 'std' is the table in the same database "test.db"

It works fine in local WAMP server, but it is not working after hosting it in Linux/Cpanel. I appreciate your help.

  • Thanks

Add $methods and $tables array and $table_prefix

I would like to add a $tables array with allowed tables and a possible $table_prefix in the code.

Suggested approach:

  • add $tables array and $table_prefix variable after the $dsn variable
  • add static function Allowed in ArrestDB class which checks if a certain table is available in the $tables array and otherwise exits with a 403 (just like for the $clients array)
  • add '$table = $table_prefix.$table; ArrestDB::Allowed($table);' to each ArrestDB::Serve function implementation

Can I add it and is this the right approach?

Unable to login with blank database password

Recently i was trying to configure your plugin with my local database which was having password as blank. Your reg-expression was not able to work without password. So i need to tweak the code to make project running.

getting service unavailable error

ArrestDB is giving the error message "Service Unavailable" and I can't figure out what I might be doing wrong.

My config:
PHP 5.5 on LAMP (Ubuntu)
PDO enabled
$dsn = 'mysql://root:vertrigo@]localhost:443/viewfind/';
.htaccess just as presented in the example, in arrestDB directory
I can see the db (viewfind) and table (stories) using a mysql client with same credentials

trying a simple get:
http://localhost/php/arrestDB/stories/

I get:
{
"error": {
"code": 503,
"status": "Service Unavailable"
}
}

I would appreciate any help in troubleshooting. Thanks!

Backbone & PUT requests

First off I absolutely love this. I haven't been able to find anything like it, says so much time making my backend api. with backbone my put request are being sent perfectly fine, though I keep getting conflict error. Other methods works fine with the backbone models, but saving a model that updates the backend, it where it goes wrong, the query string for mysql has all the data but my values, just abunch of question marks. (Do these get replaced before executing the query)

Bad request with postgresql

Hi,

I am trying to hook ArrestDB to postgresql 9.1. I put the correct DSN and have the rewriting set up, but when doing any requests I get error 400. What could be wrong?

503 Service Unavailable

Hello AlixAxel,

Thank you for this tool - it is exactly what I need and I truly appreciate the work you've put into it.

I read from your docs that Apache is optional, so I'm choosing to use iis 8 and that seems to be working. I'm getting a consistent 503 on connection attempts though. I have verified with other tools that the mysql db is accessible, and tried all obvious variations including ip addresses, servername, no port, test db, verified user/pass etc ... no luck.

Login sample is :
$dsn = 'mysql://dbusername:dbpassword@localhost/dbname/;';
$clients = array
(
);

Any suggestions as to where I'm going wrong?
Thanks Again - Paul.

Support for UUID

I sugest to support UUID in the format 1854a179-9f10-11e4-8072-000c297121a8 as id values.

Working with angualrJS Resource

http://'+location.hostname+'/ArrestDB-master/Orders/115528/

The orderID is dynamic and so we can't hardcode it. Can we call the resource like this ? please let me know

var formServicesModule = angular.module('formServicesModule',['ngResource']);

formServicesModule.factory('getFormResourceSvc', ['$resource',
function($resource){
return {
getformData: $resource('http://'+location.hostname+'/ArrestDB-master/Orders/')
};
}
]);
getFormResourceSvc.getformData.get({kp_OrderID:$stateParams.orderID},function(response) {
console.info(response);
$scope.formData = response[0];

Problemas com o postgres

Olá,

Tive alguns problemas com a base postgre, para os quais fiz as seguintes alterações para que funcionasse sem problemas:

Alterações para aperfeiçoamento do postgre:

  • Adicionado teste de "is_numeric($data)" na linha 72 para poder trabalhar melhor com colunas que sejam inteiras e não utilizar "LIKE" no "WHERE"
  • Removidas as aspas "´" e "`" para funcionamento correto
  • Suprimida a opção "PDO::ATTR_AUTOCOMMIT => true" na linha 573 para correção de bug na conexão do PDO

As alterações que efetuei:

  • Adicionado teste de tipo para verificar se for inteiro e poder utilizar campos com nomes diferentes de id no get, sem prejuízos a consulta no postgresql
    if (is_numeric($data))
    $query[] = sprintf('WHERE %s = ?', $id);
    else
    $query[] = sprintf('WHERE %s LIKE ?', $id);
  • Bug na Classe/Driver que não permite trocar o tipo de autocommit
    $options += array
    (
    \PDO::ATTR_AUTOCOMMIT => true,
    );

correct .htaccess ?

First of all: this lib is very important in that it could level the ground for pluging other databases into an app (think easy commutation to CouchDB) or exposing the DB to Mobile App more easily.

Now: I have put the index.php locally at say http://localhost/folder/db/ and changed the $dsn to what it needs.

I have tried:
http://localhost/folder/db/
response:
{
"error": {
"code": 400,
"status": "Bad Request"
}
}

http://localhost/folder/db/
response:
Error 404

Then put in the "db" directory an .htaccess from https://github.com/gilbitron/Arrest-MySQL/blob/master/.htaccess

did not solve the issue.

solutions?

"Service Unavailable"

@alixaxel
thank you for sharing this service.
but I always get 503 error "Service Unavailable"

my $dsn variable can't pass this preg_match()
'~^(mysql|pgsql)://(?:(.+?)(?::(.+?))?@)?([^/:@]++)(?::(\d++))?/(\w++)/?$~i'

my $dsn = 'mysql://[malo[:123456]@]localhost[:8080]/test/';

I'm sorry this sounds sooo rocky!!

I even tried the defualt dsn 'mysql://[user[:pass]@]host[:port]/db/'; written in the documents
I tried it @ http://www.phpliveregex.com/ but still can't make it work.

thank you in advance.

503 - Service Unavailable

Hi,

Can you please help me resolve 503 Service Unavailable error when I hosted it a domain:
http://xyz.net/apps/ArrestDB//

None of these Sqlite Path didn't work in index.php:
$dsn = 'sqlite://./test.db'
$dsn = 'sqlite://./public_html/apps/ArrestDB/test.db.db'
$dsn = 'sqlite:///home/user/public_html/apps/ArrestDB/test.db.db'

Empty client:
$clients = [];

All other files in that folder has full(755,777) permissions.

ArrestDB + Postgresql + Nginx

We are trying hard from last two weeks to configure ArrestDB with Postgresql on Nginx server. We get following error:

{
"error": {
"code": 400,
"status": "Bad Request"
}
}

while requesting like: http://serverip/ArrestDB/index.php/users

Note: We have successfully deployed this API with Postgresql on Apache server.

POST return ID of newly created record?

Currently a successful POST is returning: {success: {code: 201, status: "Created"}}

Is it possible for the ID to be returned also, so I can use it right away?

I did this: simon-lang@58ee661

But not sure if it's a good idea, so have not submitted as a pull request. (disclaimer: totally untested on tables that do not have an id column or auto-increment id)

equal and like LINE 44

  • LINE 44
    • sprintf('WHERE "%s" %s ?', $id, (ctype_digit($data) === true) ? '=' : 'LIKE'),

ctype_digit is checking if string = only digits
if true it get a equal otherwise a LIKE

  • situation
    • tbl_name, col_name and entry = 00001-Name

so i do a request for 00001

  • expected
    • SELECT * FROM tbl_name WHERE col_name LIKE '%00001%'
    • result: 1
  • get
    • SELECT * FROM tbl_name WHERE col_name = '00001'
    • result: 0
  • database type
    • mysql

perhaps you should change the /(#any)/(#any)/(#any) on #Line 39 to /(#any)/(#any)/(#operator)/(#any)

How to GET multiple records

Hi,

Is there any solution to get multiple records for GET? May like /table/id/(3,4) or /gapp/id[3,4] ?

This is another common use case and would be great if you can implement it.

  • Thanks

replace #num by #any

I think you shouldn't restrict the type of field you use as the unique identifier for a resource. I would replace all #num by #any.

swallowing exception !!!

This is a very good project, but frankly I just lost hours because you're hiding exceptions, line 577.
Print down exceptions, find a way to log them... Easier to diagnose drivers and database errors !

CORS

Hi there! Great Project!

I have a question regarding how to disable the blocking of CORS requests.
I know that I can do someting like this which helps for all GET requests:
php header("Access-Control-Allow-Origin: *");
But I think there is a better option to do so which also includes POST requests?

Thank you in advance for any advice!

HTTP_CONTENT_TYPE !!!

You shout add the HTTP_CONTENT_TYPE.
here:
if (((array_key_exists('CONTENT_TYPE', $_SERVER) === true)||(array_key_exists('HTTP_CONTENT_TYPE', $_SERVER) === true)) && (empty($data) !== true))
{
if ((strncasecmp($_SERVER['CONTENT_TYPE'], 'application/json', 16) === 0)||(strncasecmp($_SERVER['HTTP_CONTENT_TYPE'], 'application/json', 16) === 0))

I couldn't push the changes.

A question about numeric data

Hi,
in your example output, it seems that numeric fields (creditLimit and salesRepEmployeeNumber) is exported as text fields:

[
{
    "id": "114",
    "customerName": "Australian Collectors, Co.",
    "contactLastName": "Ferguson",
    "contactFirstName": "Peter",
    "phone": "123456",
    "addressLine1": "636 St Kilda Road",
    "addressLine2": "Level 3",
    "city": "Melbourne",
    "state": "Victoria",
    "postalCode": "3004",
    "country": "Australia",
    "salesRepEmployeeNumber": "1611",
    "creditLimit": "117300"
},
...

]

It should be (without double quotes):

[
{
    "id": "114",
    "customerName": "Australian Collectors, Co.",
    "contactLastName": "Ferguson",
    "contactFirstName": "Peter",
    "phone": "123456",
    "addressLine1": "636 St Kilda Road",
    "addressLine2": "Level 3",
    "city": "Melbourne",
    "state": "Victoria",
    "postalCode": "3004",
    "country": "Australia",
    "salesRepEmployeeNumber": 1611,
    "creditLimit": 117300
},
...

]

Am I wrong? I have the some result with sqlite db of mine with all numeric fields.

Thank you

PHP 5.3 tips?

Great little library.

Unfortunately my host supports PHP 5.3 max so was wondering what key features of 5.4 I would need to target.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.