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 Gadgetto
      SnipWire - Snipcart integration for ProcessWire
      Snipcart is a powerful 3rd party, developer-first HTML/JavaScript shopping cart platform. SnipWire is the missing link between Snipcart and the content management framework ProcessWire.
      With SnipWire, you can quickly turn any ProcessWire site into a Snipcart online shop. The SnipWire plugin helps you to get your store up and running in no time. Detailed knowledge of the Snipcart system is not required.
      SnipWire is free and open source licensed under Mozilla Public License 2.0! A lot of work and effort has gone into development. It would be nice if you could donate an amount to support further development:

      Status update links (inside this thread) for SnipWire development
      2020-04-06 -- SnipWire 0.8.6 (beta) released! Adds support for Snipcart subscriptions and also fixes some problems 2020-03-21 -- SnipWire 0.8.5 (beta) released! Improves SnipWires webhooks interface and provides some other fixes and additions 2020-03-03 -- SnipWire 0.8.4 (beta) released! Improves compatibility for Windows based Systems. 2020-03-01 -- SnipWire 0.8.3 (beta) released! The installation and uninstallation process has been heavily revised. 2020-02-08 -- SnipWire 0.8.2 (beta) released! Added a feature to change the cart and catalogue currency by GET, POST or SESSION param 2020-02-03 -- SnipWire 0.8.1 (beta) released! All custom classes moved into their own namespaces. 2020-02-01 -- SnipWire is now available via ProcessWire's module directory! 2020-01-30 -- SnipWire 0.8.0 (beta) first public release! (module just submitted to the PW modules directory) 2020-01-28 -- added Custom Order Fields feature (first SnipWire release version is near!) 2020-01-21 -- Snipcart v3 - when will the new cart system be implemented? 2020-01-19 -- integrated taxes provider finished (+ very flexible shipping taxes handling) 2020-01-14 -- new date range picker, discount editor, order notifiactions, order statuses, and more ... 2019-11-15 -- orders filter, order details, download + resend invoices, refunds 2019-10-18 -- list filters, REST API improvements, new docs platform, and more ... 2019-08-08 -- dashboard interface, currency selector, managing Orders, Customers and Products, Added a WireTabs, refinded caching behavior 2019-06-15 -- taxes provider, shop templates update, multiCURL implementation, and more ... 2019-06-02 -- FieldtypeSnipWireTaxSelector 2019-05-25 -- SnipWire will be free and open source Plugin Key Features
      Fast and simple store setup Full integration of the Snipcart dashboard into the ProcessWire backend (no need to leave the ProcessWire admin area) Browse and manage orders, customers, discounts, abandoned carts, and more Multi currency support Custom order and cart fields Process refunds and send customer notifications from within the ProcessWire backend Process Abandoned Carts + sending messages to customers from within the ProcessWire backend Complete Snipcart webhooks integration (all events are hookable via ProcessWire hooks) Integrated taxes provider (which is more flexible then Snipcart own provider) Useful Links
      SnipWire in PW modules directory SnipWire Docs (please note that the documentation is a work in progress) SnipWire @GitHub (feature requests and suggestions for improvement are welcome - I also accept pull requests) Snipcart Website  
      ---- INITIAL POST FROM 2019-05-25 ----
       
    • By bernhard
      #######################
      Please use the new RockFinder2
      #######################
      WHY?
      This module was built to fill the gap between simple $pages->find() operations and complex SQL queries.
      The problem with $pages->find() is that it loads all pages into memory and that can be a problem when querying multiple thousands of pages. Even $pages->findMany() loads all pages into memory and therefore is a lot slower than regular SQL.
      The problem with SQL on the other hand is, that the queries are quite complex to build. All fields are separate tables, some repeatable fields use multiple rows for their content that belong to only one single page, you always need to check for the page status (which is not necessary on regular find() operations and therefore nobody is used to that).
      In short: It is far too much work to efficiently and easily get an array of data based on PW pages and fields and I need that a lot for my RockGrid module to build all kinds of tabular data.

      Basic Usage

       
      Docs & Download
      https://modules.processwire.com/modules/rock-finder/
      https://github.com/BernhardBaumrock/RockFinder
       
      Changelog
      180817, v1.0.6, support for joining multiple finders 180810, v1.0.5, basic support for options fields 180528, v1.0.4, add custom select statement option 180516, change sql query method, bump version to 1.0.0 180515, multilang bugfix 180513, beta release <180513, preview/discussion took place here: https://processwire.com/talk/topic/18983-rocksqlfinder-highly-efficient-and-flexible-sql-finder-module/
    • By MoritzLost
      TrelloWire
      This is a module that allows you to automatically create Trello cards for ProcessWire pages and update them when the pages are updated. This allows you to setup connected workflows. Card properties and change handling behaviour can be customized through the extensive module configuration. Every action the module performs is hookable, so you can modify when and how cards are created as much as you need to. The module also contains an API-component that makes it easy to make requests to the Trello API and build your own connected ProcessWire-Trello workflows.
      Features
      All the things the module can do for you without any custom code: Create a new card on Trello whenever a page is added or published (you can select applicable templates). Configure the target board, target list, name and description for new cards. Add default labels and checklists to the card. Update the card whenever the page is updated (optional). When the status of the card changes (published / unpublished, hidden / unhidden, trashed / restored or deleted), move the card to a different list or archive or delete it (configurable). You can extend this through hooks in many ways: Modifiy when and how cards are created. Modify the card properties (Target board & list, title, description, et c.) before they are sent to Trello. Create your own workflows by utilizing an API helper class with many convenient utility methods to access the Trello API directly. Feedback & Future Plans
      Let me know what you think! In particular:
      If you find any bugs report them here or on Github, I'll try to fix them. This module was born out of a use-case for a client project where we manage new form submissions through Trello. I'm not sure how many use-cases there are for this module. If you do use it, tell me about it! The Trello API is pretty extensive, I'll try to add some more helper methods to the TrelloWireApi class (let me know if you need anything in particular). I'll think about how the module can support different workflows that include Twig – talk to me if you have a use-case! Next steps could be a dashboard to manage pages that are connected to a Trello card, or a new section in the settings tab to manage the Trello connection. But it depends on whether there is any interest in this 🙂 Links
      Repository on Github Complete module documentation (getting started, configuration & API documentation) [Module directory pending approval] Module configuration

    • By MoritzLost
      Process Cache Control
      This module 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) Clear the ProCache page render cache (if your site is using ProCache) 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.
      Plans for improvements
      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 CHANGELOG in the repository Screenshots


    • By Macrura
      PrevNextTabs Module
      Github: https://github.com/outflux3/PrevNextTabs
      Processwire helper modules for adding page navigation within the editor.
      Overview
      This is a very simple module that adds Previous and Next links inline with the tabs on the page editor. Hovering over the tab shows the title of the previous or next page (using the admin's built in jqueryUI tooltips.)
      Usage
      This module is typically used during development where you or your editors need to traverse through pages for the purpose of proofing, flagging and/or commenting. Rather than returning to the page tree or lister, they can navigate with these links.
      Warnings
      If you are using PW version 2.6.1 or later, the system will prevent you from leaving the page if you have unsaved edits.
      For earlier versions, to avoid accidentally losing changes made to a page that might occur if a user accidentally clicks on one of these, make sure to have the Form Save Reminder module installed.
      http://modules.processwire.com/modules/prev-next-tabs/
×
×
  • Create New...