Jump to content

Module: RestApi


thomasaull

Recommended Posts

@Sebi

Really great additions !  

There is a small issue, in site/api/Routes.php, the call

require_once wire('config')->paths->RestApi . "RestApiHelper.php"; 

should be

require_once wire('config')->paths->RestApi . "classes/RestApiHelper.php";

I really like the idea of applications key. I didn't spotted problems using it yesterday but still need to be tested deeply - I have three mobile native apps in which I will test it ?

 

Quote

But @thomasaull and I are not quite sure if it makes sense to transfer these basic changes into the main module as well. Therefore we would like to hear your opinion: What do you think of the new module version? Which features would be useful for you? 

The Process Module is cool, I vote to stay with it.

 

Link to comment
Share on other sites

On 9/2/2019 at 4:01 PM, Sebi said:

In my version, BasicAuth is the preferred way to request a jwt-token. After that, you have to add the token to each request.

@Sebi, I'm trying out both the single and double JWT auth methods. Double JWT works fine in my tests.

With single JWT, it seems that when Bearer token is being ignored if it is not supplied. Meaning, if I submit a request with only an API key (no JWT token), the request is accepted. At the same time, if I submit the request with a wrong Bearer token, it responds appropriately with error 400. In my understanding, both scenarios should return a 400.

I'll perform more tests to verify and report if it really is the case or if I'm missing something.

  • Like 1
Link to comment
Share on other sites

  • 2 months later...

First of all, many thanks to @thomasaull for this awesome module.
I'm starting to develop an server-side-rendered Webapp with Sapper at the frontend and ProcessWire as the backend.
For learning the behavior of pages and fields accessed via the REST API, I started a tiny example repo here. It allows to loop through all pages and if questioned for one specific page it outputs all (no validation, if a field should be readable to the frontend users) fields of the page (with some opinionated default values). Right now it only covers "basic" text-based fields, images and Repeaters.

I was wondering if there is an easy way to check for field settings like access control, conditional visibility etc. I'm thinking about a most practical solution, which is also abstractable for further projects with totally different fields. Maybe extending the Fieldtype Classes could be a solution?

 

Link to comment
Share on other sites

Hi @joshua, thanks for finding it useful ?

Personally I mostly use the RestAPI Module to gather data from multiple sources for a single endpoint. For example a blogpost might have info about the post itself, but also might pull in additional data about the author which might live on a completely different page. However I can think of usecases like yours where bascially a dump of all the data might be useful. Unfortunately there is no built in functionality for this in the module. You could check out http://modules.processwire.com/modules/pages2-json/ which does a similar thing or the GraphQL Module (http://modules.processwire.com/modules/process-graph-ql/) also goes in this direction.

Link to comment
Share on other sites

  • 2 weeks later...

Has anyone here done multi-level endpoints (e.g. /api/firstlevel/secondlevel)?

I thought the $routes variable in Routes.php would end up looking like:

$routes = [
  ['OPTIONS', 'test', RestApiHelper::class, 'preflight', ['auth' => false]], // this is needed for CORS Requests
  ['GET', 'test', Example::class, 'test'],

  // The multi-level stuff
  'firstlevel' => [
    'secondlevel' => [
      ['OPTIONS', '', RestApiHelper::class, 'preflight', ['auth' => false]],
      ['POST', '', MyEndpoints::class, 'secondlevelHandler']
	]
  ]

  'users' => [
    ['OPTIONS', '', RestApiHelper::class, 'preflight', ['auth' => false]], // this is needed for CORS Requests
    ['GET', '', Example::class, 'getAllUsers', ["auth" => false]],
    ['GET', '{id:\d+}', Example::class, 'getUser', ["auth" => false]], // check: https://github.com/nikic/FastRoute
  ],
];

But, apparently that doesn't work. Anyone know how to do this?

Link to comment
Share on other sites

@lemgrago I think at the moment the module only supports a single depth of grouping. I did a quick check and it doesn't work for me either. If it helps you can always declare your routes like:

  'firstlevel/secondlevel' => [
    ['GET', 'endpoint', Example::class, 'test'],
  ],

  'firstlevel/another-secondlevel' => [
    ['GET', 'endpoint', Example::class, 'test'],
  ],

I might add multiple nested groups in the future

  • Like 2
Link to comment
Share on other sites

  • 2 months later...

I have been using this module for a bit now and I absolutely love it. However, I have hit a brick wall as of late when it comes to getting the path to an image. In my function getClient(), I have the following:

array_push($response->offer, [
	"client" => $offer->parent->parent->name,
	"id" => $offer->id,
    "name" => $offer->name,
    "title" => $offer->title,
    "img" => $offer->test_image->httpUrl,
    "body" => $offer->body,
]);

The image field is currently set to single value, but when I go to my endpoint, "img" is always null. When I change httpUrl to url, it only produces 

"img":"\/site\/assets\/files\/1019\/"

For the life of me I can not find what I am doing wrong. I checked the folder 1019 under files and my image is currently there. Any help on the matter would be appreciated

Link to comment
Share on other sites

Hi @louisstephens, thanks for the kind words! I remember that I had the exact same problem as you once, but I can't remember what the problem or the solution actually was. Afaik it was not an issue with the module itself but with how ProcessWire handles image paths. I think I did some digging by creating a new template and return the image path there — maybe you could try that and let me know about the result. Also you could try to experiment mit $page->of (output formatting). This might have an effect on that matter aswell.

Link to comment
Share on other sites

Thanks, I appreciate the help! I was thinking it was with ProcessWire and not with the module (thought it was best to keep this under the thread in one place). I wont pretend like I understand my "fix", but I did get it working by using 

"img" => $offer->test_image->first->httpUrl,

 

  • Like 1
Link to comment
Share on other sites

It sounds like output formatting is OFF when the data of the image is requested, therefore pw treats the data of the field as PageImagesARRAY. That's why you have to get the first item manually. This step is done automatically when output formatting is ON and your field is set to single image. 

  • Like 3
Link to comment
Share on other sites

hi,

i am trying to configure the RestApi, i made some routes and it seemed like it was working but when i edit a example function or create my own it never changes, when i change the api url, the url changes, but for instance when i do site/apiv2/test i keep getting returned: "message""test successful"

Even though i removed all the routes from my routes folder and changed the output of testfunction by adding a 1 at the end?

 

 

edit:

url i am calling dev.productnetwork.calago.nl/api-v2/test

api-v2 is responding if i change the url in settings of restapi module it stops responding on the old url and works on the new url (for instance if i were to change api-v2 to api-v3, api-v2 stops working and api-v3 starts working)

added pictures, as you can see my entire routes is commented out but it keeps returing test succesful

 

afbeelding.png.0ac66d04a91f9223c18481ab13047ce3.pngafbeelding.thumb.png.fe9a26f9023c320a5c08454992e2fae4.pngafbeelding.png.866229d833d0725b0a1d77f553928ca9.png

Link to comment
Share on other sites

1 hour ago, thomasaull said:

@calago can you provide your "routes.php" aswell as the file with the endpoint function you're calling in your route?

added it to original comment, things i have tested (removed all routes)  result: nothing changed
deleted all the cache result:nothing changed,

created a new route and echo something on call result: route works output nothing?

 

Link to comment
Share on other sites

@calago I just tried to reproduce this issue with a new installation of ProcessWire:

  1. Install ProcessWire with blank profile
  2. Install RestApi Module
  3. run `api/test` => `test successful`
  4. change endpoint to `api-v2`
  5. run `api/test` => 404 Error
  6. run `api-v2/test` => `test successful`
  7. comment out all routes in `Routes.php` and run `api-v2/test` => 500 Server error (this is expected I guess)
  8. Add new file `/site/api/AnotherExample.php`, change `Routes.php` to this:
    <?php namespace ProcessWire;
    
    require_once wire('config')->paths->RestApi . "vendor/autoload.php";
    require_once wire('config')->paths->RestApi . "RestApiHelper.php";
    
    require_once __DIR__ . "/AnotherExample.php";
    
    $routes = [
      ['GET', 'other-test', AnotherExample::class, 'other'],
    ];

    and run `api-v2/other-test` => `another example`

So basically everything is working perfectly fine on my end. I guess it's something related to your environment/installation/modules… Hard to debug, if you need more help maybe provide a test repo?

Link to comment
Share on other sites

Hi @thomasaull

Thank you for this great module!

I came across a problem. I need an endpoint where I can search after an user with his e-mail address.

So I created a new grouped Route.

My Routes.php looks like this:

<?php

require_once wire('config')->paths->RestApi . "vendor/autoload.php";
require_once wire('config')->paths->RestApi . "RestApiHelper.php";

require_once __DIR__ . "/Example.php";

$routes = [
  ['OPTIONS', 'test', RestApiHelper::class, 'preflight', ['auth' => false]], // this is needed for CORS Requests
  ['GET', 'test', Example::class, 'test'],

  'searchuser' => [
    ['OPTIONS', '', RestApiHelper::class, 'preflight', ['auth' => false]], // this is needed for CORS Requests
    ['GET', '{email}', Example::class, 'doesUserWithEmailExist', ['auth' => false]],
  ],
  
  'users' => [
    ['OPTIONS', '', RestApiHelper::class, 'preflight', ['auth' => false]], // this is needed for CORS Requests
    ['GET', '', Example::class, 'getAllUsers', ["auth" => false]],
    ['GET', '{id:\d+}', Example::class, 'getUser', ["auth" => false]], // check: https://github.com/nikic/FastRoute
  ],
];

 

My Function in Example.php looks like this:

public static function doesUserWithEmailExist($data){
    echo "<pre>";
    echo print_r($data, true);
    echo "</pre>";
    
    $data = RestApiHelper::checkAndSanitizeRequiredParameters($data, ['email|email']);

    $response = new \StdClass();

    if($data->email != "") {

        $user = wire('users')->get("template=user, email=$data->email");

        if(!$user->id) throw new \Exception('user not found');

        $response->test = $data->email;
        $response->id = $user->id;
        $response->name = $user->name;
        $response->email = $user->email;

    } else {
        throw new \Exception('Unvalid E-Mail address');
    }

    return $response;
  }

 

When calling from Browser:

1894119912_Bildschirmfoto2020-02-19um14_21_04.png.5957fb80985fda4ef2a4db9f5a546586.png

 

The Problem is, that the "@" character in the E-Mail gets stripped away and therefore the email is always wrong.

I investigated this and found out, that it is because of the wire('input')->url codepart on line 61 in the Router.php. This is stripping away the "@" character when calling.

2034847938_Bildschirmfoto2020-02-19um14_29_30.png.d30be504e2b6b88e644249d58f080aea.png

When I replace the wire('input')->url part with $_SERVER['REQUEST_URI'] it is working.

What should I do?

KR
Orkun 

Link to comment
Share on other sites

Hey @Orkun, thanks, I'm really glad this module is useful for you! The problem you run into, results from code I just copied from @LostKobrakai I think (Thx for investigating btw!).

I'm not sure if it's a good way to forward your parameter like this and I guess there's a good reason this sanitizer is in place. Imagine a user would input an email like this `user?foo=bar@test.de`, I guess it would break the API since `foo` would be interpretet as a GET Variable. A couple of suggestions:

  • Use a post request and put the email in the post body
  • URL encode your request url, this way the email *should* come through

Maybe other people have some input on this issue aswell…?

Link to comment
Share on other sites

15 hours ago, thomasaull said:

Hey @Orkun, thanks, I'm really glad this module is useful for you! The problem you run into, results from code I just copied from @LostKobrakai I think (Thx for investigating btw!).

I'm not sure if it's a good way to forward your parameter like this and I guess there's a good reason this sanitizer is in place. Imagine a user would input an email like this `user?foo=bar@test.de`, I guess it would break the API since `foo` would be interpretet as a GET Variable. A couple of suggestions:

  • Use a post request and put the email in the post body
  • URL encode your request url, this way the email *should* come through

Maybe other people have some input on this issue aswell…?

Hi @thomasaull

Thank you for your input. I choosed the POST Request way.

Routes.php

<?php

require_once wire('config')->paths->RestApi . "vendor/autoload.php";
require_once wire('config')->paths->RestApi . "RestApiHelper.php";

require_once __DIR__ . "/Users.php";

$routes = [
    'searchuser' => [
        ['OPTIONS', '', RestApiHelper::class, 'preflight'], // this is needed for CORS Requests
        ['POST', '', Handler\Users::class, 'searchByEmail'],
    ],
];

Users.php

<?php namespace Handler;

class Users { 

    public static function searchByEmail($data){

    $data = \RestApiHelper::checkAndSanitizeRequiredParameters($data, ['email|email']);

    $response = new \StdClass();

    if($data->email != "") {

        $user = wire('users')->get("template=user, email=$data->email");

        if(!$user->id) throw new \Exception('user not found');

        $response->id = $user->id;
        $response->name = $user->name;
        $response->email = $user->email;

    } else {
        throw new \Exception('Unvalid E-Mail address');
    }

    return $response;
    }


}

 

But now I have other Problem with JWT Auth.

I activated the JWT Option inside the Module Settings and remove the ["auth" => false] part from the routes (as you can see above).

And when I test in Postman it always gives me the error "No Authorization Header found" even when the Auth Header is set.

Step1: Getting JWT Token

screen1.thumb.png.b48aa31c6a4a4008306ce0a3f80e3d81.png

 

Step 2: Saving JWT Token to a Postman Global Variable

screen2.thumb.png.32120f373a638d1cdc90c75b06e2e64d.png

 

Step 3: Set the new "JWT" Global variable as Auth Header for the actual POST Request (searchbymail)

screen3.thumb.png.ee3d12b23fe7fb95cba93be05b6ed21e.png

 

Step 4: Make POST Request: Search after User with E-Mail

screen4.thumb.png.a17bc3cfa21bc20e959da20f42b31887.png

 

What I am doing wrong?

KR
Orkun

Link to comment
Share on other sites

On 2/21/2020 at 1:27 PM, thomasaull said:

@Orkun Please check the documentation:https://github.com/thomasaull/RestApi#authorization-jwt You need to set the JWT as Header name "Authorization"

Hi @thomasaull

As you can see in the second & third screenshot above, I am already setting it in Postman.

 

But perhaps I could try it with a js file localy.

Another question. How would you save the JWT Token after you have get it from the /api/auth endpoint? Cookie? Local Storage? DB? 

I mean after I got the JWT Token i need to set it for every other API Request inside the Header and for that I need to somehow save it somewhere, am I right?

KR

Orkun

Link to comment
Share on other sites

Ah sorry, I didn't catch that. Can you check in the `headers` Tab how the Header is actually set? I did check everything with Insomnia on Saturday and it worked for me … Regarding saving the JWT Token: I have been saving it in local storge, but this is considered unsafe, since third party scripts could access it (if you do not use any third party scripts, this might not be an issue). So I guess the best thing is to store it in a cookie.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...