Setup Firebase
Firebase: REST and Web API
DSCI 551
Wensheng Wu
1
Firebase
• A cloud-based platform to support web and
mobile app development
• Used to be Envolve, a startup founded in 2011
– For adding online chat functions into websites
• Later expanded into Firebase which was then
acquired by Google in 2015
2
Products
• Firebase (realtime) database
– Manage JSON documents
– Real-time syncing data between users and devices
• Firebase (cloud) storage
– Store images, photos, videos
• Firebase (user) authentication
– Support signin using Google, Facebook
3
Also has Cloud Firestore in Beta
Firebase realtime database
4
5
Create a Firebase account
• You may use your Google account
• Go to Firebase console:
– https://console.firebase.google.com/
6
https://console.firebase.google.com/
Click on “Add project”
7
8
Choose this for web app
9
Copy this &
replace the
firebaseConfig in
the sample html
file
Create a firebase realtime db
10
Realtime database
11
Choose test mode
12
13
May use this (but we expect you to
know the curl way)
14
JSON (Javascript Object Notation)
• Light-weight data exchange format
– Much simpler than XML
– Language-independent
– Inspired by syntax of JavaScript object literals
• Some differences from JavaScript objects, e.g.,
– String in JSON must be double-quoted
– Ok to single-quote in JavaScript (& Python)
15
Syntax of JSON
• value =
string|number|object|array|true|false|null
• object = {} | { members }
– members = pair | pair, members
– pair = string : value
• array = [] | [ elements ]
– elements = value | value, elements
16
These are actual values
Valid JSON or not?
• []
• {}
• {[]}
• [{}]
• {“name”: john}
• {name: “john”}
• {“name”: 25}
• “name”
• 25
• {25}
• [25]
17
JSON is case-sensitive
• Valid or not?
– True
– true
– TRUE
– Null
– false
18
Example JSON
19
Value is an array
Value is an object
Stored in Firebase
20
Note: array stored as an object
Key = index of element in array
Check syntax of JSON
• JSON validator
– http://jsonlint.com/
21
http://jsonlint.com/
Roadmap
• Firebase REST API
• Firebase Javascript API
– Useful for your project
22
curl
• Command line tool for data transfer
• Download from here (has Windows & Mac OS
versions):
– https://curl.haxx.se/download.html
• You may easily grab a copy of curl in Cygwin
(see next slide)
23
https://curl.haxx.se/download.html
Install curl in Cygwin
24
Select to install this one
Firebase REST API
• PUT & POST (C in CRUD)
• GET (R)
• PATCH (U)
• DELETE (D)
25
All request commands
are case sensitive (all uppercases)
GET
• curl ‘https://inf551-
1b578.firebaseio.com/weather.json’
• Or
– curl -X GET ‘https://inf551-
1b578.firebaseio.com/weather.json’
26
Another example
• curl -X GET ‘https://inf551-
1b578.firebaseio.com/examples/phoneNumb
ers/0.json’
– {“number”:”212 555-1234″,”type”:”home”}
27
Note: refer to array element by index
PUT
• curl -X PUT ‘https://inf551-
1b578.firebaseio.com/weather.json’ -d ‘”hot”‘
– “hot”
• PUT: write a given value (e.g., “hot”) to the
specify node (e.g., “weather”)
– Overwrite if node already has value
28
PUT
• curl -X PUT ‘https://inf551-
1b578.firebaseio.com/users/100.json’ -d
‘{“name”: “john”}’
• This will add a new node “users” (assuming it
does not exist yet) and a child of this node
with key “100” and content: {“name”: “john”}
29
Example
• Is the previous command the same as this?
– curl -X PUT -d ‘{“100”: {“name”: “John”}}’
‘https://inf551-1b578.firebaseio.com/users.json’
• Can you think of a situation where two
commands give different results?
30
Note we now write to the “users” node
https://inf551-1b578.firebaseio.com/users.json
POST
• curl -X POST -d ‘{“name”: “John”}’
‘https://inf551-
1b578.firebaseio.com/users.json’
• Note post automatically generates a new key
& then stores the value for the new key
– In contrast, PUT will simply overwrite the value
31
https://inf551-1b578.firebaseio.com/users.json
PATCH
• curl -X PATCH -d ‘{“name”: “John Smith”,
“age”: 25}’ ‘https://inf551-
1b578.firebaseio.com/users/100.json’
• PATCH performs the update if value already
exists (e.g., name) ; otherwise, it inserts the
new value (e.g., age)
– So… an upsert
32
NOTE: patch expects an JSON object in the
value
https://inf551-1b578.firebaseio.com/users/100.json
DELETE
• curl -X DELETE ‘https://inf551-
1b578.firebaseio.com/users/100.json’
• What does this do?
– curl -X DELETE ‘https://inf551-
1b578.firebaseio.com/users.json’
33
https://inf551-1b578.firebaseio.com/users.json
Query: filtering by key
• curl ‘https://inf551-
1b578.firebaseio.com/users.json?orderBy=”$k
ey”&equalTo=”200″‘
• This returns:
– {“200”:{“age”:25,”name”:”David”}}
34
Must be a string. Why?
Another example
• curl ‘https://inf551-
1b578.firebaseio.com/users.json?orderBy=”$k
ey”&startAt=”200″‘
• This returns:
– {“200”:{“age”:25,”name”:”David”},”300″:{“gender
“:”female”,”gpa”:4.0,”name”:”Mary”}}
35
Users with keys >= “200”
Ways of filtering data
• By key:
– orderBy=”$key”
• By child key:
– orderBy=”
– E.g., orderBy = “address/city”
• By value:
– orderBy=”$value”
36
Key
orderBy=”name”
Parameters
• startAt
• endAt
• equalTo
• limitToFirst
• limitToLast
37
Example: filtering by child key
• curl ‘https://inf551-
1b578.firebaseio.com/users.json?orderBy=”na
me”&limitToFirst=1&print=pretty’
• What will this return?
38
Example for orderBy=”$value”
• curl -X PUT ‘https://inf551-
1b578.firebaseio.com/users/500.json’ -d
‘{“name”: “jennifer”, “scores”: {“q1”: 5, “q2”:
10, “q3”: 8, “midterm”: 9}}’
39
Example: filtering by value
• curl ‘https://inf551-
1b578.firebaseio.com/users/500/scores.json?
orderBy=”$value”&limitToFirst=1&print=prett
y’
• What will this return?
40
Creating index for value/child key
• Specified in database rules:
– https://firebase.google.com/docs/database/security/i
ndexing-data
• Only required
for REST API
• No need to index key
– Done automatically by Firebase
41
https://firebase.google.com/docs/database/security/indexing-data
Ordering
42
https://firebase.google.com/docs/database/rest/retrieve-data#section-rest-ordered-data
Ordering
43
Watch out…
• https://firebase.google.com/docs/database/re
st/retrieve-data
44
https://firebase.google.com/docs/database/rest/retrieve-data
Using REST in Python
• import requests
– May need to “pip install requests” first
• url = ‘https://inf551-
1b578.firebaseio.com/users.json’
• response = requests.get(url)
• response.json()
– {u’200′: {u’age’: 25, u’name’: u’David’},…
45
Writing
• url1 = ‘https://inf551-
1b578.firebaseio.com/users/888.json’
• data = ‘{“name”: “jimmy”, “gender”: “male”}’
• response = requests.put(url1, data)
46
Update, delete & post
• Updating
– requests.patch(url, data)
• Deleting
– requests.delete(url)
• Posting
– Requests.post(url, data)
47
Pretty printing
• import json
• print json.dumps(response.json(), indent=4)
48
{
“200”: {
“age”: 25,
“name”: “David”
},
…
Roadmap
• Firebase REST API
• Firebase Javascript/Web API
– Useful for your project
49
50
Demo html page
51
val() returns a Javascript object
representing content of snapshot
Database reference
• firebase.database() returns a reference to the
firebase database as specified by
“firebaseConfig”
• ref(): returns a reference to the root node of
the database
• ref(“weather”) returns a reference to the
“weather” child of the root
– same as ref().child(“weather”)
52
Modify the data in database
• Observe the data automatically changed in
the browser
53
Write data using set()
• function writeUserData(userId, name, email) {
firebase.database().ref(“users/” + userId).set({
name: name,
email: email
});
}
• writeUserData(“123”, “John”, ” “);
54
Setting/overwriting the data of user 123
Write data using push() and set()
• firebase.database().ref(“users”).push().set({na
me: “John”, email: ” “});
• push() will automatically generate a key
– In this case, id for the new user
• Which REST command is this similar to?
55
Update data
• function updateUserData(userId, phone) {
firebase.database().ref(“users/”+userId).update({
phone: phone
});
}
• updateUserData(“123”, “(626)123-0000”);
56
Note this does not remove other data of user 123
What if you replace “update” with “set”?
Retrieve a list of values
• userRef = firebase.database().ref(“users”);
• userRef.on(“value”, function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key + “: ” + child.val());
});
});
57
Press Ctrl+Shift+J in Chrome for console window
Listening to child events instead
• userRef.on(“value”, function(snapshot) {…
– Will retrieve a list of values in the path specified by
userRef
– Not efficient, since entire list will be retrieved
whenever changes occur
• userRef.on(“child_added”, function(…)) {…
– Firebase will callback for every existing child and new
child added to the path userRef
– Other events: child_changed, child_removed
58
Filtering data
• queryRef =
firebase.database().ref(“users”).orderByChild(
“name”).equalTo(“David”);
• queryRef.on(“value”, function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key + “: ” + child.val());
});
});
59
Filtering data
• It also supports:
– orderByKey()
– orderByValue()
60
orderByValue() example
61
queryRef = firebase.database().ref(“users/500/scores”)
.orderByValue();
queryRef.on(“value”, function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key + “: ” + child.val());
});
});
Resources
• Add Firebase to your JavaScript Project
– https://firebase.google.com/docs/web/setup
• Getting Started with Firebase on the Web
– https://www.youtube.com/watch?v=k1D0_wFlXgo&fe
ature=youtu.be
• Realtime Database: Installation & Setup in
JavaScript, Read & Write Data …
– https://firebase.google.com/docs/database/web/start
62
https://firebase.google.com/docs/web/setup
https://firebase.google.com/docs/database/web/start
Resources
• Firebase REST API
– https://firebase.google.com/docs/reference/rest/
database/
• Requests for Python
– http://docs.python-
requests.org/en/master/user/quickstart/#make-a-
request
63
https://firebase.google.com/docs/reference/rest/database/
http://docs.python-requests.org/en/master/user/quickstart/#make-a-request