Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a GET REST API call to my Firebase database?

I have a simple Firebase Realtime database that looks like this:

My simple JSON Todo database

I created it with a PUT call using this as the body:

[{
      "complete": false,
      "editMode": false,
      "title": "Mow the lawn",
      "id": 26,
      "note": "This is a note for 27"
    },

 {
      "complete": true,
      "editMode": false,
      "title": "Feed the dog",
      "id": 27,
      "note": "This is a note for 27"
    }   
]    

I want to create a REST GET call to get the first item based on the ID (26 in this case).

My rules look like this:

{
  "rules": {
    ".read": true,
    ".write": true,
    "todos": {
      ".indexOn": ["id"]      
  }  
}
}

I tried:

https://<myid>.firebaseio.com/todos/26/id.json

but that returned null because of course that dang '0' and '1' are there.

I can do this:

https://<myid>.firebaseio.com/todos/0.json

and that returns the first item, but when I do this:

https://<myid>.firebaseio.com/todos.json

the '0' and the '1' aren't returned, so how do I know to use them?

Do you understand my confusion?

What am I missing?

like image 882
Nick Hodges Avatar asked Sep 19 '25 15:09

Nick Hodges


1 Answers

Firebase Realtime Database doesn't natively store arrays. Instead it stores the array elements in sequential keys, starting with "0".

When you request a location/query with sequential keys starting with "0" through the REST API, Firebase returns the data as an array, which is what you see when you request todo.json.

But you can address individual items in the array by their key, which is what you did by requesting todo/0.json.

All of the above gets a single node by its complete and absolute path. But it seems that what you want is to retrieve a node by querying for the value of one of its properties. To do that, you'll need to use a query.

To get the item(s) with "id" equal to 26, you can perform the following query:

https://<myid>.firebaseio.com/todos.json?orderBy="id"&equalTo=26

Since there may be multiple child nodes under todos with id equal to 26, this returns a list of such nodes. In the case of the JSON you shared:

{
  "0": {
    "complete": false,
    "editMode": false,
    "id": 26,
    ...
  }
}
like image 104
Frank van Puffelen Avatar answered Sep 21 '25 10:09

Frank van Puffelen