Jump to content
thomasaull

Module: RestApi

Recommended Posts

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

  • Like 2

Share this post


Link to post
Share on other sites

@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.

 

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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?

 

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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.

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Sounds like your test_image field is configured to return an array of results - hence access via the first accessor fixing things for you.

  • Like 1

Share this post


Link to post
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

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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?

 

Share this post


Link to post
Share on other sites

Mmmhh really weird. Can‘t spot anything wrong on first sight. 

Can you reproduce this problem on a fresh install without any other plugins?

Are you using anything cache related (Pro-Cache maybe?)

Share this post


Link to post
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?

Share this post


Link to post
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 

Share this post


Link to post
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…?

Share this post


Link to post
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

Share this post


Link to post
Share on other sites
Quote

and remove the ["auth" => false] part from the routes (as you can see above).

What happens if you set it to true?

Share this post


Link to post
Share on other sites
14 minutes ago, MadeMyDay said:

What happens if you set it to true?

It still gives the same error

Share this post


Link to post
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

Share this post


Link to post
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.

Share this post


Link to post
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

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By joshua
      This module is (yet another) way for implementing a cookie management solution.
      Of course there are several other possibilities:
      - https://processwire.com/talk/topic/22920-klaro-cookie-consent-manager/
      - https://github.com/webmanufaktur/CookieManagementBanner
      - https://github.com/johannesdachsel/cookiemonster
      - https://www.oiljs.org/
      - ... and so on ...
      In this module you can configure which kind of cookie categories you want to manage:

      You can also enable the support for respecting the Do-Not-Track (DNT) header to don't annoy users, who already decided for all their browsing experience.
      Currently there are four possible cookie groups:
      - Necessary (always enabled)
      - Statistics
      - Marketing
      - External Media
      All groups can be renamed, so feel free to use other cookie group names. I just haven't found a way to implement a "repeater like" field as configurable module field ...
      When you want to load specific scripts ( like Google Analytics, Google Maps, ...) only after the user's content to this specific category of cookies, just use the following script syntax:
      <script type="optin" data-type="text/javascript" data-category="statistics" data-src="/path/to/your/statistic/script.js"></script> <script type="optin" data-type="text/javascript" data-category="marketing" data-src="/path/to/your/mareketing/script.js"></script> <script type="optin" data-type="text/javascript" data-category="external_media" data-src="/path/to/your/external-media/script.js"></script> <script type="optin" data-type="text/javascript" data-category="marketing">console.log("Inline scripts are also working!");</script> The type has to be "optin" to get recognized by PrivacyWire, the data-attributes are giving hints, how the script shall be loaded, if the data-category is within the cookie consents of the user. These scripts are loaded asynchronously after the user made the decision.
      If you want to give the users the possibility to change their consent, you can use the following Textformatter:
      [[privacywire-choose-cookies]] It's planned to add also other Textformatters to opt-out of specific cookie groups or delete the whole consent cookie.
      You can also add a custom link to output the banner again with a link / button with following class:
      <a href="#" class="privacywire-show-options">Show Cookie Options</a> <button class="privacywire-show-options">Show Cookie Options</button> This module is still in development, but we already use it on several production websites.
      You find it here: PrivacyWire Git Repo
      Download as .zip
      I would love to hear your feedback 🙂
      CHANGELOG
      0.0.5 Multi-language support included completely (also in TextFormatter). Added possibility to async load other assets (e.g. <img type="optin" data-category="marketing" data-src="https://via.placeholder.com/300x300">) 0.0.4 Added possibility to add an imprint link to the banner 0.0.3 Multi-language support for module config (still in development) 0.0.2 First release 0.0.1 Early development
    • By MoritzLost
      This is a new module that provides a simple solution to clearing all your cache layers at once, and an extensible interface to perform various cache-related actions.
      The simple motivation behind this module was that I was tired of manually clearing caches in several places after deploying a change on a live site. The basic purpose of this module is a simple Clear all caches link in the Setup menu which clears out all caches, no matter where they hide. You can customize what exactly the module does through it's configuration menu:
      Expire or delete all cache entries in the database, or selectively clear caches by namespace ($cache API) Clear the the template render cache. Clear out specific folders inside your site's cache directory (/site/assets/cache) Refresh version strings for static assets to bust client-side browser caches (this requires some setup, see the full documentation for details). This is the basic function of the module. However, you can also add different cache management action through the API and execute them through the module's interface. For this advanced usage, the module provides:
      An interface to see all available cache actions and execute them. A system log and logging output on the module page to see verify what the module is doing. A CacheControlTools class with utility functions to clear out different caches. An API to add cache actions, execute them programmatically and even modify the default action. Permission management, allowing you granular control over which user roles can execute which actions. The complete documentation can be found in the module's README.
      Beta release
      Note that I consider this a Beta release. Since the module is relatively aggressive in deleting some caches, I would advise you to install in on a test environment before using it on a live site.
      Let me know if you're getting any errors, have trouble using the module or if you have suggestions for improvement!
      In particular, can someone let me know if this module causes any problems with the ProCache module? I don't own or use it, so I can't check. As far as I can tell, ProCache uses a folder inside the cache directory to cache static pages, so my module should be able to clear the ProCache site cache as well, I'd appreciate it if someone can test that for me.
      Future plans
      If there is some interest in this, I plan to expand this to a more general cache management solution. I particular, I would like to add additional cache actions. Some ideas that came to mind:
      Warming up the template render cache for publicly accessible pages. Removing all active user sessions. Let me know if you have more suggestions!
      Links
      https://github.com/MoritzLost/ProcessCacheControl ProcessCacheControl in the Module directory

    • By David Karich
      Admin Page Tree Multiple Sorting
      ClassName: ProcessPageListMultipleSorting
      Extend the ordinary sort of children of a template in the admin page tree with multiple properties. For each template, you can define your own rule. Write each template (template-name) in a row, followed by a colon and then the additional field names for sorting.
      Example: All children of the template "blog" to be sorted in descending order according to the date of creation, then descending by modification date, and then by title. Type:
      blog: -created, -modified, title  Installation
      Copy the files for this module to /site/modules/ProcessPageListMultipleSorting/ In admin: Modules > Check for new modules. Install Module "Admin Page Tree Multible Sorting". Alternative in ProcessWire 2.4+
      Login to ProcessWire backend and go to Modules Click tab "New" and enter Module Class Name: "ProcessPageListMultipleSorting" Click "Download and Install"   Compatibility   I have currently tested the module only under PW 2.6+, but think that it works on older versions too. Maybe someone can give a feedback.     Download   PW-Repo: http://modules.processwire.com/modules/process-page-list-multiple-sorting/ GitHub: https://github.com/FlipZoomMedia/Processwire-ProcessPageListMultipleSorting     I hope someone can use the module. Have fun and best regards, David
    • By dimitrios
      Hello,
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version (has been tested up to v3.3), add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "https://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      Usage
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
       
      Download
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.


×
×
  • Create New...