This document explains how to configure Firebase as a REST API, as well as some common pain points and tips.
Follow this steps:
- Create an account on Firebase
- Note: setup is very straight forward & at the moment it doesn't require payment details.
-
Go to the console (https://console.firebase.google.com/)
-
Click "Create a project"
-
Choose a name for your project
-
Google Analytics: you can disable it (we will not use it)
-
Click "Create project"
-
Firebase will the start the initial setup (this will take ~1 minute)
-
In the sidebar, select
Build > Realtime Database
Important
In this document, we will use a "Realtime Database", not "Firestore Database"
- Click: "Create Database"
- Select location (e.g. Europe)
- For security rules, select the option "Start in locked mode"
-
To give public access to all users, you can use these settings:
{ "rules": { ".read": true, ".write": true } }
- Click "Publish"
Warning
With the configuration above, we're allowing public access to our databse (anyone with the url can potentially add data and modify data in our database). Depending on your use case, you may need more strict rules.
If you've followed the steps above, Firebase will automatically expose a REST API.
First of all, you'll need the base url. You'll find it in the Firebase interface:
API URL:
- The api url for each resource looks like
baseURL/resource.json
Example endpoints:
- GET
/recipes.json
- GET
/recipes/:recipeId.json
- POST
/recipes.json
- PATCH
/recipes/:recipeId.json
(there’s also PUT) - DELETE
/recipes/:recipeId.json
PATCH vs. PUT:
- PATCH will update an existing resource partially
- PUT updates a resource entirely
Firebase doesn't follow all the conventions that you see in most REST APIs. Here's a list with the main things to keep in mind:
- List of items: Firebase returns an object (instead of an array)
- Example: a GET request to
/projects.json
will return an object instead of an array (in the section below, you'll find some hints to convert it to an array).
- Example: a GET request to
- Wrong request: if you send a request to the wrong URL, on the browser you may get a CORS error (instead of a 404).
- Example: if you send a request to
/projects.json/42
instead of/projects/42.json
- Example: if you send a request to
- If a list of items is empty: Firebase will return null (instead of an empty array)
- If an item does not exist: Firebase will return null (instead of a 404 error)
- Resource created: Firebase returns a 200 (instead of a 201)
When you get a list of items (for example, a GET request to /projects.json
), Firebase returns an object instead of an array.
You can convert this object to an array with the following syntax:
const projectsArr = Object.keys(projectsObject).map((id) => ({
id,
...projectsObject[id],
}));