Jump to content

New Module: AppApi


Sebi

Recommended Posts

Thanks @androbey, I found the folder api in site and the Example.php file. I'll try things out 🙂

EDIT:

I went through the Routs.php and tested example.com/api/test and in the browser I got "message: test successful"

But when I try /processwire/setup/appapi I get Unrecognized path.

In order to get it in the admin page, do I first have to edit the Routs.php file? Because in the manual I didn't see something like that or I have over seen it.

Best,

Marcel

Link to comment
Share on other sites

Hi everyone!

First, my two cents to @androbey: my first guess would be that maybe the spaces are not escaping correctly? Spaces in GET parameters need to be converted to %20. So "This is a test" becomes "q=this%20is%20a%20test" in the URL. Depending on the framework you use for your api request, this conversion may not happen automatically. In Javascript, for example, there is the encodeURIComponent() function that can do this conversion for you. In PHP there is the function urlencode() which does the same. Can you get further with it?

Now to @Marcel: The message "no endpoint defined" already shows that the module was installed correctly. This message comes from the default route definition:

['*', '', AppApiHelper::class, 'noEndPoint', ['auth' => false]]

And I can also tell you already that you are sending a valid api key along. Otherwise you would get an error message "Apikey not valid".

Next, you can call /api/auth once. This request will return the current user. Without auth token this should be the guest user:

{
  "id": 40,
  "name": "guest",
  "loggedIn": false
}

After that you can start implementing your own endpoints. Here in the wiki you can find everything you need to know: https://github.com/Sebiworld/AppApi/wiki/3.0:-Creating-Endpoints

EDIT @Marcel: Sorry, I did not see you last comment. Routes.php does only influence your endpoints. The admin-page should be created automatically during installation and should be accessible in the "setup" header menu. I appended a screenshot from a German-translated backend. "Verwaltung" means "setup". Maybe you have to delete and re-install AppApi if the page was not created automatically...

Bildschirmfoto 2021-10-23 um 13.50.08.png

Edited by Sebi
Link to comment
Share on other sites

Hi @Sebi,

thank you for your response. That was the first thing I checked. 
For the API request I am using vanilla JS (fetch) and I'm using the encodeURIComponent() function. Also in network tab in dev tools I can see the request is transmitted as it should be according to RFC 3986. I would digg deeper, but I don't know where the status code gets injected for a (in fact) successful request. 

Link to comment
Share on other sites

1 hour ago, androbey said:

For the API request I am using vanilla JS (fetch) and I'm using the encodeURIComponent() function. Also in network tab in dev tools I can see the request is transmitted as it should be according to RFC 3986. I would digg deeper, but I don't know where the status code gets injected for a (in fact) successful request. 

Hey @androbey, I tried a few things and definitely found inconsistencies. It looks like spaces, but also other characters (e.g. "+") in the url path cause weird behavior.

In any case, any GET parameters that might be appended then seem to be ignored. At /api/search/my%20test?test=1 I cannot find the GET parameter test in $_GET of PHP. I can't tell exactly where this behavior is coming from (FastRoute? PHP? Apache?), but it probably won't work to specify the search string as you intended.

If you specify it as a GET parameter (/api/search?q=my%20test) instead, it works without problems. The corresponding route definition would look like this:

'search' => [
        ['GET', '', Search::class, 'getSearchResults', ["auth" => true]],
],

 

  • Like 1
Link to comment
Share on other sites

Great news! Version 1.2.0 is here!
The changes in the code are actually not huge, but all the bigger are the additional possibilities we have now: With the new version, modules can register their own endpoints. These endpoints are then merged with the traditional definition in Routes.php.

You may ask: But @Sebi, why are you so excited about this? Well. This means that endpoints can now be easily installed and updated. And we can now easily share our great and useful endpoints with the ProcessWire community!

I'll get started then: My first AppApi module is AppApiFile. This module provides the /file endpoint for retrieving files uploaded to ProcessWire pages. 

I have extended the wiki with a small tutorial and sample code for creating an AppApi module:
https://github.com/Sebiworld/AppApi/wiki/4.0:-AppApi-Modules

I can't wait to see what you people will do with it! 🥳

  • Like 4
Link to comment
Share on other sites

There was still a small problem that prevented the module from being automatically updated from within ProcessWire.
I had renamed the root branch in Github from master to main, but then the download path in the ProcessWire module directory didn't fit anymore.

Long Story Short: Now everything works again 🙂

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...

@Sebi How to set the "API Endpoint" module configuration correctly? I need to create a website (subdomain) that is an API server only, no web pages will be served from there.. I test the parameter like "/" in order to works like: https://api.domain.com/users/ but this show a "404 Not Found".. I need the endpoint entry of the API in the "home" of the website

Link to comment
Share on other sites

Hi @Pixrael

At the moment, this is not possible. In the AppApi module, a route must be specified that is not yet occupied by a classic ProcessWire route. AppApi uses a hook on 404 (Page not found) error and then replaces the return with the AppApi content. 

I am facing a similar problem right now. I would like to use ProcessWire exclusively as a headless CMS for an app. If you have access to the domain and subdomain settings, it might work to run ProcessWire under a subdomain and link the main domain to /api.

However, I've been thinking for a while about how to add api responses to existing ProcessWire pages (e.g. the root page under "/").

Link to comment
Share on other sites

2 hours ago, Sebi said:

At the moment, this is not possible. In the AppApi module, a route must be specified that is not yet occupied by a classic ProcessWire route. AppApi uses a hook on 404 (Page not found) error and then replaces the return with the AppApi content. 

Just wondering whether URL Path Hooks would be of help in this respect?

https://processwire.com/blog/posts/pw-3.0.173/#introducing-url-path-hooks

Link to comment
Share on other sites

33 minutes ago, kongondo said:

Just wondering whether URL Path Hooks would be of help in this respect?

https://processwire.com/blog/posts/pw-3.0.173/#introducing-url-path-hooks

@kongondo This does not work, these new hook functions only work when the requested URLs are not mapped directly to a page and the home page is "always there".

@Sebi Could it be possible to use the homepage template file to "wireIncludeFile" the routes file, or to directly pass the request to your module, ex. initialize a module static function with the input object? AppApi::Execute($input);

Link to comment
Share on other sites

@Pixrael What I do on ProcessPageView::pageNotFound is calling this function:

	public function ___handleApiRequest(HookEvent $event) {
		if ($this->checkIfApiRequest()) { 			// Check if the current REQUEST_URI starts with /api
			$this->apiCall = true;					
			Auth::getInstance()->initApikey();		// Init authentication
			$router = new Router();					// Init Router
			$router->go($this->registeredRoutes);	// Start resolving the route. This function will echo() and
													// exit()
			$event->replace = true;					// Only needed in hook-function-call
		}
	}

In theory (not tested yet), it should work to copy the three relevant lines (Init Auth, Init Router, Resolve Route) to your home-template file. I would be really interested to know if it really works out that way. Don't have time to test it out right now.

This is my plan for a future module-update:
- Extend the routes definition that it is not only applied to the api endpoint from the module configuration but to the whole pagetree
- Check also on existing pages, not only in the 404 hook, if a route matches. If a valid api key is present, output the AppApi response instead. 
- Otherwise everything remains the same

Link to comment
Share on other sites

50 minutes ago, Sebi said:

@Pixrael What I do on ProcessPageView::pageNotFound is calling this function:

	public function ___handleApiRequest(HookEvent $event) {
		if ($this->checkIfApiRequest()) { 			// Check if the current REQUEST_URI starts with /api
			$this->apiCall = true;					
			Auth::getInstance()->initApikey();		// Init authentication
			$router = new Router();					// Init Router
			$router->go($this->registeredRoutes);	// Start resolving the route. This function will echo() and
													// exit()
			$event->replace = true;					// Only needed in hook-function-call
		}
	}

In theory (not tested yet), it should work to copy the three relevant lines (Init Auth, Init Router, Resolve Route) to your home-template file. I would be really interested to know if it really works out that way. Don't have time to test it out right now.

This is my plan for a future module-update:
- Extend the routes definition that it is not only applied to the api endpoint from the module configuration but to the whole pagetree
- Check also on existing pages, not only in the 404 hook, if a route matches. If a valid api key is present, output the AppApi response instead. 
- Otherwise everything remains the same

Yes, it works with this three lines in the home template file, but you must enable the urlSegments in the home template.. now the AppApi configuration still have the "domain.com/api/users" as endpoint but "domain.com/users/" works too.. if you try "domain.com/foo/" the api respond with a 404 json response

  • Thanks 1
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
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By Marco Ro
      Hi guys!
      I'm a bit anxious because this is the first module I present! (beta modulo) But I will finally be able to share something with the community too! :)
      This is a BETA version of the PayPal payment system called: PayPal Commerce Platform.
      It is an advanced system (Business Pro account is needed) that brings various benefits in terms of fees and above all integrates direct payment with credit/debit cards. 
      The module integrates with Padloper 0.0.2, which is the current installation I'm using.
      This system integrates the classic PayPal buy button, the alternative or local payment method and the new payment system: credit/debit cards that doesn't go through the PayPal account. It is a Stripe-style payment, it connects directly with the bank and integrates 3D security validation.
      I say that it is a BETA because this module currently only works with Sandbox account, to put it live you need to change API url manually (manually for the moment).
      Because this module is not ready for live:
      I would like to have your opinion on how I built the module (is the first one I do). I don't want to share something that is not fish but I need a comparison with someone more experienced than me, for be sure that this is the best way to code the module.
      If you want to try this I created a git, you will find all the instructions for installation and correct operation. (Git has a MIT licensed)
      https://github.com/MarcooRo/processwire-PayPal-Commerce-Platform I hope I did something that you guys can like :)
    • 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 !)
      FieldtypeQRCode
      Github: https://github.com/romaincazier/FieldtypeQRCode
      Modules directory: https://processwire.com/modules/fieldtype-qrcode/
      A simple fieldtype generating a QR Code from the public URL of the page, and more.
      Using the PHP library QR Code Generator by Kazuhiko Arase.

      Options
      In the field’s Details tab you can change between .gif or .svg formats. If you select .svg you will have the option to directly output the markup instead of a base64 image. SVG is the default.
      You can also change what is used to generate the QR code and even have several sources. The accepted sources (separated by a comma) are: httpUrl, editUrl, or the name of any text/URL/file/image field.
      If LanguageSupport is installed the compatible sources (httpUrl, text field, ...) will return as many QR codes as there are languages. Note however that when outputting on the front-end, only the languages visible to the user will be generated.
      Formatting
      Unformatted value
      When using $page->getUnformatted("qrcode_field") it returns an array with the following structure:
      [ [ "label" => string, // label used in the admin "qr" => string, // the qrcode image "source" => string, // the source, as defined in the configuration "text" => string // and the text used to generate the qrcode ], ... ] Formatted value
      The formatted value is an <img>/<svg> (or several right next to each other). There is no other markup.
      Should you need the same markup as in the admin you could use:
      $field = $fields->get("qrcode_field"); $field->type->markupValue($page, $field, $page->getUnformatted("qrcode_field")); But it’s a bit cumbersome, plus you need to import the FieldtypeQRCode's css/js. Best is to make your own markup using the unformatted value.
      Static QR code generator
      You can call FieldtypeQRCode::generateQRCode to generate any QR code you want. Its arguments are:
      string $text bool $svg Generate the QR code as svg instead of gif ? (default=true) bool $markup If svg, output its markup instead of a base64 ? (default=false) Hooks
      Please have a look at the source code for more details about the hookable functions.
      Examples
      $wire->addHookAfter("FieldtypeQRCode::getQRText", function($event) { $page = $event->arguments("page"); $event->return = $page->title; // or could be: $event->return = "Your custom text"; }) $wire->addHookAfter("FieldtypeQRCode::generateQRCodes", function($event) { $qrcodes = $event->return; // keep everything except the QR codes generated from editUrl foreach($qrcodes as $key => &$qrcode) { if($qrcode["source"] === "editUrl") { unset($qrcodes[$key]); } } unset($qrcode); $event->return = $qrcodes; })
    • By Sebi
      AppApiFile adds the /file endpoint to the AppApi routes definition. Makes it possible to query files via the api. 
      This module relies on the base module AppApi, which must be installed before AppApiFile can do its work.
      Features
      You can access all files that are uploaded at any ProcessWire page. Call api/file/route/in/pagetree?file=test.jpg to access a page via its route in the page tree. Alternatively you can call api/file/4242?file=test.jpg (e.g.,) to access a page by its id. The module will make sure that the page is accessible by the active user.
      The GET-param "file" defines the basename of the file which you want to get.
      The following GET-params (optional) can be used to manipulate an image:
      width height maxwidth maxheight cropX cropY Use GET-Param format=base64 to receive the file in base64 format.
    • By MarkE
      This fieldtype and inputfield bundle was built for storing measurement values within a field, rendering them in a variety of formats and converting them to other units or otherwise modifying them via the API.
      The API consists of a number of predefined functions, some of which include...
      render() for rendering the measurement object, valueAs() for converting the value to another unit value, convertTo() for converting the whole measurement object to different units, and add() and subtract() for for modifying the stored value by the value (converted as required) in another measurement. In the admin the inputfield includes a checkbox (which can be optionally disabled) for converting values on page save. For an example if a value was typed in as centimeters, the unit was changed to metres, and the page saved with this checkbox selected, said value would be automatically converted so that e.g. 170 cm becomes 1.7 m.

      A simple length field using Fieldtype Measurement and Inputfield Measurement.
      Combination units (e.g. feet and inches) are also supported.
      Please note that this module is 'proof of concept' at the moment - there are limited units available and quite a lot of code tidying to do. More units will be added shortly.
      See the GitHub at https://github.com/MetaTunes/FieldtypeMeasurement for full details and updates.
    • By tcnet
      File Manager for ProcessWire is a module to manager files and folders from the CMS backend. It supports creating, deleting, renaming, packing, unpacking, uploading, downloading and editing of files and folders. The integrated code editor ACE supports highlighting of all common programming languages.
      https://github.com/techcnet/ProcessFileManager

      Warning
      This module is probably the most powerful module. You might destroy your processwire installation if you don't exactly know what you doing. Be careful and use it at your own risk!
      ACE code editor
      This module uses ACE code editor available from: https://github.com/ajaxorg/ace

      Dragscroll
      This module uses the JavaScript dragscroll available from: http://github.com/asvd/dragscroll. Dragscroll adds the ability to drag the table horizontally with the mouse pointer.
      PHP File Manager
      This module uses a modified version of PHP File Manager available from: https://github.com/alexantr/filemanager
       
×
×
  • Create New...