Skip to content

2.1: Api Keys

Sebastian Schendel edited this page Dec 31, 2020 · 4 revisions

Whichever of the three ways you choose, every application needs its own api-keys. Each request to your api has an api-key, that links it to its application.

As of version 1.1.0, this is no longer quite true. It is possible to define an application that accepts all requests that do not provide an API key. More about this below. However, I would not recommend this for most applications.

Click on "Add new Apikey" on the bottom of the application form. Notice, that you must save a newly generated application once before that is possible.

A new apikey has a prefilled randomly generated key per default, but you can set it to any value you want. I recommend, to generate a new apikey per version of your app. That makes you able to revoke older apikeys. You can easily name your apikey like your version to make it clearer to understand. Additionally you can give your apikey a predefined expiry date.

To use an apikey for a request, you have to set it to the X-API-KEY-header.

This is, how you can do it with the Angular HttpClient:

this.httpClient.get('https://my-website.dev/api/auth', {
  'x-api-key': 'ytaaYCMkUmouZawYMvJN9',
});

If you don't like that your api is available under /api/, you can change that in the module's settings to a custom path if you want to.

By the way: If something goes wrong, you will get an informative error-message. If you are a superuser or your site runs in debug-mode, you will get even more information like this:

{
  "error": "Apikey not valid.",
  "devmessage": {
    "class": "ProcessWire\\AppApiException",
    "code": 401,
    "message": "Apikey not valid.",
    "location": "/Users/sebi/Developer/Test/my-website.local/site/modules/AppApi/classes/Router.php",
    "line": 130
  }
}

Generally speaking, you can count on consistent errors and status-codes from the module, which makes interacting with the api much easier. Read more about that in the section Error Handling.

Default application

It is possible to define an application that accepts all requests that do not provide an API key. In most use cases, I would recommend using an apikey. The apikey is another factor to protect the api against unauthorized access. And you can always delete a compromised apikey afterwards and thus make it invalid.

If you really need an api that is responsive without further action, you can set an application in the edit view as the "default application". Only one application can be responsible for requests without an apikey. If you check this, all other applications will be unchecked automatically.


➡️ Continue with 2.2: PHP-Session
⬅️ Back to 2.0: Defining Applications