News:

Want to get involved in developing SMF, then why not lend a hand on our github!

Main Menu

SMF 2.0 "REST" API

Started by Andre N, November 10, 2011, 09:29:31 PM

Previous topic - Next topic

Andre N

I made this "REST" API for SMF that will work with SMF 2.x that might be helpful to someone.
The reason REST is in quotes is it's not a true RESTful API but it will allow you to use the API and SSI functions on your SMF installation from a different domain. It will also let you create posts, send pm's and it is easy to extend to do other things...

How to use:
Download the two attachments here, the client and server. Extract the server package and upload it somewhere on your SMF forum domain.

In the api folder, open the SmfRestServer.php file and on line 47 specify your SECRET_KEY. Make it secure!! A long string that nobody will guess. Save it and upload it to the api folder.

Open the file SmfRestClient.php and on line 52, set the path to your api folder, the one you just uploaded.

Upload the file SmfRestClient.php somewhere, it doesn't need to be on the same domain as the api server folder.

Now you are ready to call the API. You do this by first including the file SmfRestClient.php :

require_once('SmfRestClient.php');


then you will instantiate the SmfRestClient object like this:

$secretKey = 'sdgefgbdbdvberger4564trgdfgdfvcvv';
$api = new SmfRestClient($secretKey);

Be sure you set the $secretKey variable to be your unique secret key that you set above.

Now you can use the API functions by calling them like this:

$api->login_user('andre');


You can get the results/output of your API call like this:

$result = $api->get_userInfo();

the results will be a stdClass Object by default.

If you instantiate the API client with the parameter 'raw' like this:

$api = new SmfRestClient($secretKey, 'raw');

you will get the output as an array instead.

:)
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

Robert.

Nice work and thanks for sharing :D

zakaluka

Very nice!  Thanks a lot of creating this.

Regards,

z.

orjank

Hi, and thanks for creating this.

I've been trying to integrate smf 2.0.1 with my own site for a while now, and jfusion just isn't cutting it in my case - especially as I am gunning for a frameless integration. My setup is as follows:

SMF is located as follows on my site: www. mydomain. com/sitename/smf/
I put the client file at : www. mydomain. com/sitename/smf/SmfRestClient.php
Your api folder is at : www. mydomain. com/sitename/smf

The client file points to the api folder with the API_SERVER define, and my own site attempts the following:

require_once( './smf/SmfRestClient.php' );
$secretKey = 'SomeKindaSecretKeyGoesHere';
$api = new SmfRestClient( $secretKey );
$success = $api->login_user( 'someusername' );
$result = $api->get_userInfo();


The secret key is the same between the code above and the one specified in SmfRestServer.php, but my problem is that both api calls fail with

Unknown method sitename_smf_api_login_user was called

and

Unknown method sitename_smf_api_get_userInfo was called

... respectively

Any idea what I am doing wrong? Thanks in advance.. :p


Best regards,
Orjan

Andre N

That error message is being thrown by the SmfRestServer.php file because for some reason it's not parsing the request url correctly in the getRoute() function of that file.
the code

protected function getRoute()
    {
        $cwd   = getcwd();
        $cwd   = str_replace($_SERVER['DOCUMENT_ROOT'], '', $cwd);
        $route = str_replace($cwd, '', $_SERVER['REQUEST_URI']);
       
        if ('/' == substr($route, 0, 1)) {
            $route = substr($route, 1);
        }
       
        $this->route = $route;

        return $this;
    }


is getting 'sitename/smf/api/get/userInfo' as the request string instead of 'get/userInfo' which is what it should be in order to create the correct function name.

It looks like getcwd() is giving the wrong current directory, in which case you could set $cwd manually in that function to be '/sitename/smf/api' (or use chdir())

Try that and see if it helps :)
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

ankifreeze

hi I want to integrate mysite with smf forum in order member in mysite don't need to login twice ... but I got problem.....I using this...require_once('SmfRestClient.php');

$secretKey = '123456';
$api = new SmfRestClient($secretKey);

$api->get_userInfo();

$api->authenticate_user('greenhorse', '123456');

but  it doesn't work?
I think after I using it I don't need login in smf forum anymore.....any suggestion? :(

Andre N

#6
Hi,

This login doesn't set the login cookie on the user browser, it set's it in curl's cookiejar, and the login is only going to be valid for the current API session. Theoretically you could use curl to login and set the login cookie like jquery does, but I haven't had time to mess with it.
It also won't log the user out, as it is intended to run from a different domain and cross-domain policy won't let you delete the cookie. Again, maybe this can be done with curl.

If you're on the same domain, use the regular API, which will let you login and logout easily.
http://www.simplemachines.org/community/index.php?topic=453008.0
Otherwise I'd recommend examining jquery's smf login method and duplicating that.
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

ankifreeze

hi..yes I using forum and mysite in same domain.... I have used your api but it doesn't work.... :(

log out function doesn't work....

require_once ( 'smf_2_api.php');
smfapi_logout('[email protected]');



login function also doesn't work...


require_once ( 'smf_2_api.php');
smfapi_authenticate('ankifreeze', '123456')






Andre N

hi, I will reply to your usage of the regular API in it's thread ;)
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

newbieuser202

Hi,

I've installed a new copy of SMF (v.2.0.2) and used your "REST" api.  I tried the very basic function which is login below is the code and results I received.


require_once('SmfRestClient.php');

$secretKey = 'sdgefgbdbdvberger4564trgdfgdfvcvv';
$api = new SmfRestClient($secretKey);
$result = $api->login_user('[email protected]');
print_r($result);


And the result when i user print_r is

stdClass Object ( [data] => true [error] => )


Can you point me where I should check for the error since the code does not log in the user to the SMF forum. 

Thank you,

NB

Andre N

Hi,
There was no error; that is the correct output. The user is logged in through the API only, ie. the cookie is set on the server for the API to use for the duration of the session. The cookie isn't set locally which means if you browse to your forum the user won't be logged in because the cookie isn't set locally.

If you try the other functions you'll see the user is logged in according to the API and you'll be able to access their data, edit, and do whatever you like. Because of cross-domain limitations you won't be able to set login cookie (or delete it, logout) for a user.

If you are on the same domain I recommend you use this version of the API which does not have this limitation and is easier to use as it's only one script:
http://www.simplemachines.org/community/index.php?topic=453008.0

If that is not an option, you might be able to trick SMF into setting the cookie (or deleting it) locally by using cURL to send the login information to your SMF login address. That is the method used by JFusion and seems like it would work , however I haven't had any success doing it yet.
The idea would be to take your SMF login location www.yourforum.com/index.php?action=login2
and cURL the post data, username and password to it and the cookie should be set by SMF.
It would be a nice feature to have and I'll play with it when I get a chance, but if you have any success please post back :)
"Every generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?"

bidulemachin

Hi,

I have noticed there was a little bug (well in my version).
in SmfRestServer, in the getMethod(), the method was including the first slash, so it was trying to call "_" and then the actual method. So "_authenticate_user" for example.

I changed the code to be that to make it work:
       
$method       = str_replace('/', '_', $parts[0]);
        if(substr($method, 0 ,1) == '_')
        $method = substr($method, 1, strlen($method));

        $this->method = $method;

Sunchaser

Hi, i am trying to integrate a game with the SMF forum v 2.0.2 using the REST API.

I think the function getMethod() is broken, as it tries to search for the wrong method.

Example, if i call

$api -> get_user()

the getMethod search for

smf_api_get_user

while it should search (accordingly to the last version of smf_2_api.php for:

smfapi_getUserData

I would like to know if someone has a version of SmfRestServer.php fixed.

Thanks


garycarr

I am trying to setup this API and I am unclear on how the api talks to the SMF installation. In the instructions above I see no way to tell the Rest api where to find SMF and how to connect to it.

Kindred

The API file called settings.php...
Слaва
Украинi

Please do not PM, IM or Email me with support questions.  You will get better and faster responses in the support boards.  Thank you.

"Loki is not evil, although he is certainly not a force for good. Loki is... complicated."

garycarr

I have create a test script to test connectivity using the API


require_once('SmfRestClient.php');
$secretKey = 'mykey';
$api = new SmfRestClient($secretKey);


$result = $api->check_ifOnline('username');
print_r($result);


I have enabled API_DEBUG in the SmfRestClient.php and the following url gets returned.

www.domain.com/forums/api/check/ifOnline.json?secretKey=mykey&identifier=username


I am not getting any data returned from the API.

I have manually set the path the Settings.php

// specify the settings path here if it's not in smf root and you want to speed things up
$settings_path = $_SERVER['DOCUMENT_ROOT'] . /path/to/forums/Settings.php



Can anyone point to in the direction of what I might be missing?


Thank You in advance!

Thorney

It's all Greek to me! I'll show my co-admin this, he's much better at the coding stuff than I am!

hebelehubele

I use this api for login outside to SMF forum.
require_once('forum/SmfRestClient.php');
$secretKey = 'sdgefgbdbdvberger4564trgdfgdfvcvv';
$api = new SmfRestClient($secretKey);
$api->login_user("master");
$result = $api->get_userInfo();
var_dump($result);


But result is return NULL...

I want one login form which I was created that login users into my site also SMF forum.

Kindred

ummm...   If I read it correctly, you are doing the exact opposite. You are attempting to get the SMF user data, not set it...
Слaва
Украинi

Please do not PM, IM or Email me with support questions.  You will get better and faster responses in the support boards.  Thank you.

"Loki is not evil, although he is certainly not a force for good. Loki is... complicated."

Advertisement: