3 min read

How to use API Authentication

Every API is different when it comes to Authentication but in Directus, all you need is a Bearer token.
Authenticate with a Token

Every API is different when it comes to Authentication but in Directus, all you need is a Bearer token. You can create once in Directus by using an API user with  a token defined in the User Management portal. This token is used in the authentication header.

To use Authentication with the API, you must include the Authorization HTTP header with the value Bearer followed by your token.

Authorization: Bearer your-bearer-token

Postman is very useful API playground where you can try different ideas before including them in your project. Create a new Collection and open the Authorization tab. Paste your token into the Token field at the bottom.

Authorization example in Postman

Now you can add new Requests inside your Collection which will use these Authentication settings.

For you application or website, you need to include the token for every API query by using the authorization header. Here is an example of a simple GET query on my articles collection.

curl -H "Authorization: Bearer your-bearer-token" https://directus.example.com/items/articles?fields=id,title,author.first_name
?
I'm writing these commands below in raw curl which can be easily translated into your chosen language.

Security

It is good practice to create several access tokens that are restricted for the task at hand. For example, use a "read-only" access token for your website or if you have multiple sites, use a unique access token for each website. Then use a separate access token for the backend scripts that need to write back to Directus. This will help keep your application secure.

To acheive this, you'll need to create a role and specifiy what collections that role can read, write, update or delete. Then assign that role to your API user.

Everything you need to know about Directus Roles
Roles are a core feature of Directus which controls how your users interact with the data. Learn how you can use roles to build a successful team and secure your application.

Conclusion

Now you know how to authenticate your API query and secure your application using different roles. Use the links below for further reading.

How to use Postman with Directus
Postman is an essential tool in any project. You can connect the Directus API and test out the various endpoints and responses.
How to use Directus REST API on your website?
REST APIs are a very powerful method for retrieving your data from Directus. In this article, I’ll show you how you can query, create, update and delete records as well as some advanced techniques that will be useful when creating websites.

By continuing to use our website, you consent to use essential cookies. We also use optional tracking cookies which help us gather statistics to improve our services. Do you consent to these cookies?

I Consent Do not track