Rest Api building in less than 5 minutes with Strapi 2020
In this post I will show you how to have an api builder ready to use with https://strapi.io/
Requirements
- nodejs ≥ 10
- some database like mysql. I tried with mongo with no luck. You could use docker https://gist.github.com/jrichardsz/73142c5c7eb7136d80b165e75d3a1e22
Step 1: Database initialization
Just connect to your mysql using some IDE like https://dbeaver.io/ to validate credentials and create a database
Step 2: Create strapi project
In some folder of your disk, execute
npx create-strapi-app my-project
Select custom installation , mysql and enter your database parameters:
- Choose your installation type Custom (manual settings)
- Choose your default database client mysql
- Database name: strapi
- Host: 192.168.1.5
- Port: 3306
- Username: root
- Password: ******
- Enable SSL connection: No (i think yes for mysql production instances)
NOTE: Database must already exist
If everything is ok, you must have this log:
Creating a project with custom database options.
Creating files.
Dependencies installed successfully.
Your application was created at /../my-project.
Available commands in your project:
npm run develop
Start Strapi in watch mode.
npm run start
Start Strapi without watch mode.
npm run build
Build Strapi admin panel.
npm run strapi
Display all available commands.
You can start by doing:
cd /../my-project
npm run develop
Step 3: Start up and create an admin user
- execute npm run develop
- go to http://localhost:1337
- a minimal wizard will ask you for the initialization of administrator credentials
- go again http://localhost:1337 and use your recently admin credentials
Step 4: Create an entity or resource
In an api vocabulary, an entity or resource is the core. For strapi is called Collection. You will be prompted after your first login with the create collection form. You can skip this step and select yourself in :
Content-Types Builder >> Create new collection type
Wizard is intuitive. You just need to set the name, and add some fields and finish.
Then you need to add your fields
For this post I created a book collection with two fields: author & title. Don’t forget to click o “save”. This final operation will create the sql table.
To add data (books), go to Content Manager, click on your collection and click on “Create new entry”:
Finally, you should save and publish (important)
Step 5: Add security to your api
If you try to list all books using the rest api, you will see this error
To fix it, you just need to configure anonymous or public access.
Go to “Settings”, click on “Roles” under “Users & Permissions plugin” section and click on “Public”
And choose the operations as you like and save. For this post at least click on “Find”
After that , if you perform a simple HTTP GET invocation to http://localhost:1337/books (using curl , web browser or postman) and you will get the data registered:
Also another operations are available. Check the following table for a restaurants example
This rest endpoints are ready to use in any app or startup:
- web (react, angular, vue, linkstart, etc)
- backend (java, nodejs, etc)
- android & ios
Here ends the 5 minutes post!!!
More Security
If the previous public example does not meet your security expectations, strapi offer you an 02 options to protect the rest api. Both are based in oauth2:
- Api Token: I’m not sure but this is a kind of OAuth 2.0 Client Credentials Grant. Basically a token is generated ready to be used on any http client (postman, curl, soapui, insomnia) or source code (java, python, nodejs, etc). This is suitable for backend development. Not for web applications.
- User & password : Based on OAuth 2.0 Password Grant. In which you need to create a specific user, add a role to it and specify which collections and operations are allowed. This is perfect for web applications with a proper login
If you choose one of these options, don’t forget to remove the public permissions
Security option #1 : Api Token
This is so easy thanks to the intuitive user interface:
- Click on Settings > Api Token
- Set a name & description
- Token duration & token type
- Choose your collection and set the allowed operations
- Click on save
After that, the token is showed. Save it because it will be hidden if you go to another page
After that, you could use this token as Authorization Bearer to fetch your books
Security option #1 : User & Password
This is more complicated and needs more steps.
Steps 1 : Create the role
In the 2020 version, you could create roles for free. In the 2023 version, a payed subscription is required. And is good for such a ready to use platform.
For 2023 version, you should edit one of the existent roles and add the required permissions
At the moment of this writing, I was not able to choose only read or create operations for the selected role. So, User with this role, will be able to create, list, delete and update the books
For 2020 version
Just select “Roles & Permissions” on Plugin section and click on “Add new role”
Choose a name and select operations over book collection as you like and save:
Left empty another configurations in role settings!!
Step 2: Create user
Just select User predefined collection and click on “Add new user”
Enter a username, password, email , confirmed on, blocked off and save
Step 3: Get a token
With a success user creation, you just need to perform a simple post to get a new token:
curl http://localhost:1337/auth/local \
-d ‘{“identifier”:”web_server@mail.com”,”password”:”****”}’ \
-H “Content-type:application/json”
identifier could be the username o email. You will get a json with the precious token in jwt field:
{
“jwt”: “eyJzI1****”,
“user”: {
“id”: 1,
“username”: “web_server”,
“email”: “web_server@mail.com”,
“provider”: “local”,
“confirmed”: true,
“blocked”: false,
“role”: {
“id”: 3,
“name”: “web_server_read”,
“description”: “”,
“type”: “web_server_read”
},
“created_at”: “2020–05–14T02:33:47.000Z”,
“updated_at”: “2020–05–14T02:54:10.000Z”
}
}
Step 4: Use the token to consume Api
This is easy. You just need to send the obtained jwt as Authorization bearer header:
curl localhost:1337/books -H “Authorization:Bearer eyJzI1****”
This security is ready to use in any of your applications.
That’s all!
References
Strapi installation
Roles and permissions
Authentication endpoints
CRUD ready to use endpoints
Strapi with docker
Add relations between collections
What’s next
- boilerplate ready to use with mysql (skip installation steps)
- heroku template