How to quickly make a CRUD REST API and database with Firebase
Have you ever needed a quick, free, online database with an easy CRUD REST API? Here’s how to do it in 3 steps and about 5 minutes using Firebase.
Step 1: Setup your database
- Create a new project in the Firebase console.
- Set up a Realtime Database in your Firebase project. Set permissions to public read/write (you’ll lock these down in step 3).
- Copy the address for your database. It will look like: https://[PROJECT_ID].firebaseio.com
Step 2: CRUD your data
Write data to a specific node/location in database
From your command line, execute a cURL (obviously replacing the domain part of the URL in the command with the address to your database):
curl -X PUT -d '{ "first": "Jack", "last": "Sparrow" }' \
'https://[PROJECT_ID].firebaseio.com/users/jack/name.json'
Get data from that node
curl 'https://[PROJECT_ID].firebaseio.com/users/jack/name.json'
Also if the database is set to public read/write, you can just hit that URL in your browser to see the contents at that node.
Push data to a node
Note, this is different than the write/put to a specific node. This will create a new node (with a unique ID) under the node you supply. Then it will place your data in that new node.
curl -X POST -d '{"user_id" : "jack", "text" : "Ahoy!"}' \
'https://[PROJECT_ID].firebaseio.com/message_list.json'
The response body will contain the ID of the newly created node:
{ "name": "-INOQPH-aV_psbk3ZXEX" }
Delete a node
curl -X DELETE \
'https://[PROJECT_ID].firebaseio.com/users/jack/name/last.json'
For more commands, see the Firebase REST Reference: https://firebase.google.com/docs/reference/rest/database
Step 3: Lock down your database
Finally, you’ll want to prevent unauthorized read/write access to your publicly-available database.
1. Copy the Database Secret Token Key from the Service Accounts section of your Firebase project.
2. Update your Database Rules to require authenticated requests.
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
3. Adjust your cURL commands to include the Database Secret Token Key. For example:
curl -X PUT -d '{ "first": "Jack", "last": "Sparrow" }' \
'https://[PROJECT_ID].firebaseio.com/users/jack/name.json?auth=[DATABASE_SECRET_TOKEN_KEY]'
And that’s it. Your database should now be secure behind that token. If needed, you can revoke that token and issue a new one at any time in your Service Accounts section.