Jump to content

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

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

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

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?

 

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?

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 

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…?

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

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

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.

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 FireWire
      Hello community!

      I want to share a new module I've been working on that I think could be a big boost for multi-language ProcessWire sites.

      Some background, I was looking for a way for our company website to be efficiently translated as working with human translators was pretty laborious and a lack of updating content created a divergence between languages. I, and several other devs here, have talked about translation integrations and have recognized the power that DeepL has. DeepL is an AI deep learning powered service that delivers translation quality beyond any automated service available. After access to the API was opened up to the US, I built Fluency, a DeepL translation integration for ProcessWire.
      Fluency brings automated translation to every multi-language field in the admin, and also provides a translation tool allowing the user to translate their text to any language without it being inside a template's field. With Fluency you can:
      Translate any plain textarea or text input Translate any CKEditor content (yes, with markup) Translate page names for fully localized URLs on every page Translate your in-template translation function wrapped strings Translate modules Fluency is free, and now so is DeepL
      Since this module was first built DeepL has introduced free Developer accounts that allow anyone to start using Fluency at zero cost and beginning with the version 0.3.0 release Fluency now supports free DeepL accounts. As of June 2021 DeepL supports translation to 26 languages and continues to offer more!
      Installation and usage is completely plug and play. Whether you're building a new multi-language site, need to update a site to multi-language, or simply want to stop manually translating a site and make any language a one-click deal, it could not be easier to do it. Fluency works by having you match the languages configured in ProcessWIre to DeepL's. You can have your site translating to any or all of the languages DeepL translates to in minutes (quite literally).
      Let's break out the screenshots...
      When the default language tab is shown, a message is displayed to let users know that translation is available. Clicking on each tab shows a link that says "Translate from English". Clicking it shows an animated overlay with the word "Translating..." cycling through each language and a light gradient shift. Have a CKEditor field? All good. Fluency will translated it and use DeepL's ability to translate text within HTML tags. CKEditor fields can be translated as easily and accurately as text/textarea fields.

      Repeaters and AJAX created fields also have translation enabled thanks to a JavaScript MutationObserver that searches for multi-language fields and adds translation as they're inserted into the DOM. If there's a multi-language field on the page, it will have translation added.

      Same goes for image description fields. Multi-language SEO friendly images are good to go.

      Creating a new page from one of your templates? Translate your title, and also translate your page name for native language URLs. (Not available for Russian, Chinese, or Japanese languages due to URL limitations). These can be changed in the "Settings" tab for any page as well so whether you're translating new pages or existing pages, you control the URLs everywhere.

      Language configuration pages are no different. Translate the names of your languages and search for both Site Translation Files (including all of your modules)

      Translate all of the static text in your templates as well. Notice that the placeholders are retained. DeepL is pretty good at recognizing and keeping non-translatable strings like that. If it is changed, it's easy to fix manually.

      Fluency adds a "Translate" item to the CMS header. When clicked this opens up a modal with a full translation tool that lets the user translate any language to any language. No need to leave the admin if you need to translate content from a secondary language back to the default ProcessWire language. There is also a button to get the current API usage statistics. DeepL account owners can set billing limitations via character count to control costs. This may help larger sites or sites being retrofitted keep an eye on their usage. Fluency can be used by users having roles given the fluency-translate permission.

      It couldn't be easier to add Fluency to your new or existing website. Simply add your API key and you're shown what languages are currently available for translation from/to as provided by DeepL. This list and all configuration options are taken live from the API so when DeepL releases new languages you can add them to your site without any work. No module updates, just an easy configuration. Just match the language you configured in ProcessWire to the DeepL language you want it to be associated with and you're done. Fluency also allows you to create a list of words/phrases that will not be translated which can prevent items such as brands and company names from being translated when they shouldn't

       
      Limitations:
      No "translate page" - Translating multiple fields can be done by clicking multiple translation links on multiple fields at once but engineering a "one click page translate" is not feasible from a user experience standpoint. The time it takes to translate one field can be a second or two, but cumulatively that may take much longer (CKEditor fields are slower than plain text fields). There may be a workaround in the future but it isn't currently on the roadmap. No "translate site" - Same thing goes for translating an entire website at once. It would be great, but it would be a very intense process and take a very (very) long time. There may be a workaround in the future but it isn't on the roadmap. No current support for Inline CKEditor fields - Handling for CKEditor on-demand hasn't been implemented yet, this is planned for a future release though and can be done. I just forgot about it because I've never really used that feature personally.. Alpha release - This module is in alpha. Releases should be stable and usable, but there may be edge case issues. Test the module thoroughly and please report any bugs via a Github issue on the repository or respond here. Please note that the browser plugin for Grammarly conflicts with Fluency (as it does with many web applications). To address this issue it is recommended that you disable Grammarly when using Fluency, or open the admin to edit pages in a private window where Grammarly may not be loaded. This is an issue that may not have a resolution as creating a workaround may not be possible. If you have insight as to how this may be solved please visit the Github page and file a bugfix ticket.
      Requirements:
      ProcessWire  3.0+ UIKit Admin Theme That's Fluency in a nutshell. A core effort in this module is to create it so that there is nothing DeepL related hard-coded in that would require updating it when DeepL offers new languages. I would like this to be a future-friendly module that doesn't require developer work to keep it up-to-date.
      The Module Is Free
      This is my first real module and I want to give it back to the community as thanks. This is the best CMS I've worked with (thank you Ryan & contributors) and a great community (thank you dear reader).
      DeepL Developer Accounts
      In addition to paid Pro Developer accounts, DeepL now offers no-cost free accounts. Now all ProcessWire developers and users can use Fluency at no cost.
      Learn more about free and paid accounts by visiting the DeepL website. Sign up for a Developer account, get an API key, and start using Fluency today.
      Download & Feedback
      Download the latest version here
      https://github.com/SkyLundy/Fluency-Translation/archive/main.zip
      Github repository:
      https://github.com/SkyLundy/Fluency-Translation
      File issues and feature requests here (your feedback and testing is greatly appreciated):
      https://github.com/SkyLundy/Fluency-Translation/issues
       
      Thank you! ¡Gracias! Ich danke Ihnen! Merci! Obrigado! Grazie! Dank u wel! Dziękuję! Спасибо! ありがとうございます! 谢谢你!

    • By monollonom
      (once again I was surprised to see a work of mine pop up in the newsletter, this time without even listing the module on PW modules website 😅. Thx @teppo !)
      Github: https://github.com/romaincazier/FieldtypeQRCode
      Modules directory: https://processwire.com/modules/fieldtype-qrcode/
      This is a simple module I made so a client could quickly grab a QR Code of the page's url in the admin.
      There's not much to it for now, but if need be you can output anything using a hook:
      $wire->addHookAfter("FieldtypeQRCode::getQRText", function($event) { $event->return = "Your custom text"; }) You can also output the QR code on your front-end by calling the field:
      echo $page->qr_code_field; The module uses the PHP library QR Code Generator by Kazuhiko Arase. When looking for a way to generate a QR Code in PW I came across @ryan's integration in his TFA module. I'm not very familiar with fieldtype/inputfield module development so I blindly followed @bernhard (great) tutorial and his BaseFieldtypeRuntime. At some point I'll take a deeper look to make a module on my own.
      Some ideas for improvements :
      add the ability to choose what to ouput : page's url / editUrl / file(s) / image(s) / ... allow to output multiple QR codes ?
    • By Chris Bennett
      https://github.com/chrisbennett-Bene/AdminThemeTweaker
      Inspired by @bernhard's excellent work on the new customisable LESS CSS getting rolled into the core soon, I thought I would offer up the module for beta testing, if it is of interest to anyone.

      It takes a different approach to admin styling, basically using the Cascade part of CSS to over-ride default UiKit values.
      Values are stored in ModuleConfig Module creates a separate AdminThemeTweaker Folder at root, so it can link to AdminThemeTweaker.php as CSS AdminThemeTweaker.php reads the module values, constructs the CSS variables then includes the CSS framework Can be switched on and off with a click. Uninstall removes everything, thanks to bernhard's wonderful remove dir & contents function.
      It won't touch your core. It won't care if stuff is upgraded. You won't need to compile anything and you don't need to touch CSS unless you want to.

      It won't do much at all apart from read some values from your module config, work out the right CSS variables to use (auto contrast based on selected backgrounds) and throw it on your screen.
      You can configure a lot of stuff, leave it as it comes (dark and curvy), change two main colors (background and content background) or delve deep to configure custom margins, height of mastheads, and all manner of silly stuff I never use.

      Have been developing it for somewhere around 2 years now. It has been (and will continue to be) constantly tweaked over that time, as I click on something and find something else to do.
      That said, it is pretty solid and has been in constant use as my sole Admin styling option for all of those 2 years.

      If nothing else, it would be great if it can provide any assistance to @bernhard or other contributor's who may be looking to solve some of the quirkier UiKit behavior.
      Has (in my opinion) more robust and predictable handling of hidden Inputfields, data-colwidths and showIf wrappers.
      I am very keen to help out with that stuff in any way I can, though LESS (and any css frameworks/tools basically) are not my go.
      I love CSS variables and banging-rocks-together, no-dependency CSS you can write with notepad.



       

    • By opalepatrick
      I see old posts saying that repeaters are not the way to go in Custom Process Modules. If that is the case, when using forms (as I am trying to do) how would one tackle things like repeat contact fields where there can be multiple requirements for contact details with different parameters? (Like point of contact, director, etc) or even telephone numbers that have different uses?
      Just for background I am creating a process module that allows me to create types of financial applications in the admin area (no need to publish any of this, pure admin) that require a lot of personal or company information.
      Maybe I am thinking about this incorrectly?
    • By HMCB
      I ran across a reference to IftRunner module. The post was 6 years ago. I cant find it in available modules. Has it been pulled?
×
×
  • Create New...