Firebase: REST and Web API
DSCI 551
Wensheng Wu
1
CRUD in REST
• CRUD
– C – create PUT/POST (verbs in HTTP)
– R – retrieve/read GET
– U – update PATCH
– D – delete DELETE
• ordering and filtering
– orderBy="$key"
– orderBy="$value"
– orderBy="name"
– startAt=25, endAt=25, equalTo=25, equalTo="john"
– limitToFirst=1, limitToLast=1
2
New filtering
• startAfter
– startAfter=25 (for > 25)
– startAt=25 (>= 25)
• endBefore
– endBefore=25 (< 25)
– endAt=25 (<= 25)
3
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
4
Products
Also has Cloud Firestore in Beta
• 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
5
Firebase realtime database
6
7
Create a Firebase account
• You may use your Google account
• Go to Firebase console:
– https://console.firebase.google.com/
8
Click on "Add project"
9
Create a firebase realtime db
10
Realtime database
11
Choose test mode
12
Open to access forever
• note .read and .write have a value of true
db-URL/users.json?orderBy="name"
this index supports this orderBy
13
14
May use this (but we expect you to
know the curl way)
15
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)
16
Syntax of JSON
These are actual values
• value =
string|number|object|array|true|false|null
• object = {} | { members }
– members = pair | pair, members
– pair = string : value
• array = [] | [ elements ]
– elements = value | value, elements
17
Valid JSON or not?
• [2, "john"]
• {}
• {"name":[]}
• [{}]
• {[]}
• {"name": john}
• {name: "john"}
• {"name": 25}
• "name"
• 25
• {25}
• [25]
18
JSON is case-sensitive
• Valid or not?
– True
– true
– TRUE
– Null
– false
19
Example JSON
Value is an object
Value is an array
20
Stored in Firebase
Note: array stored as an object
Key = index of element in array
21
Check syntax of JSON
• JSON validator
– http://jsonlint.com/
22
Roadmap
• Firebase REST API
• Firebase Javascript API
– Useful for your project
23
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)
• You may also use curl on EC2 pre-installed…
24
Install curl in Cygwin
Select to install this one
25
Firebase REST API
• PUT & POST (C in CRUD)
• GET (R)
All request commands
are case sensitive (all uppercases)
• PATCH (U)
• DELETE (D)
26
GET
• curl 'https://inf551-
1b578.firebaseio.com/weather.json'
• Or
– curl -X GET 'https://inf551-
1b578.firebaseio.com/weather.json'
27
Another example
• curl -X GET 'https://inf551-
1b578.firebaseio.com/examples/phoneNumb
ers/0.json'
– {"number":"212 555-1234","type":"home"}
Note: refer to array element by index
28
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
29
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"}
30
Example
• Is the previous command the same as this?
– curl -X PUT -d '{"100": {"name": "John"}}'
'https://inf551-1b578.firebaseio.com/users.json'
Note we now write to the "users" node
• Can you think of a situation where two
commands give different results?
31
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
32
PATCH
NOTE: patch expects an JSON object in the
value
• 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
33
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'
34
Query: filtering by key
• curl 'https://inf551-
1b578.firebaseio.com/users.json?orderBy="$k
ey"&equalTo="200"'
Must be a string. Why?
• This returns:
– {"200":{"age":25,"name":"David"}}
35
Another example
• curl 'https://inf551-
1b578.firebaseio.com/users.json?orderBy="$k
ey"&startAt="200"'
Users with keys >= "200"
• This returns:
– {"200":{"age":25,"name":"David"},"300":{"gender
":"female","gpa":4.0,"name":"Mary"}}
36
Ways of filtering data
Key
• By key:
– orderBy="$key"
orderBy="name"
• By child key:
– orderBy="<path-to-child-key>“
– E.g., orderBy = “name”
• By value:
– orderBy="$value"
37
Parameters
• startAt
• endAt
• equalTo
• limitToFirst
• limitToLast
• startAfter
• endBefore
38
Example: filtering by child key
• curl 'https://inf551-
1b578.firebaseio.com/users.json?orderBy=“ag
e"&limitToFirst=1&print=pretty’
• What will this return?
39
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}}'
40
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?
41
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
42
Ordering
43
Ordering
44
Watch out…
• https://firebase.google.com/docs/database/re
st/retrieve-data
45
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'},…
46
Writing
• url1 = 'https://inf551-
1b578.firebaseio.com/users/888.json'
• data = '{"name": "jimmy", "gender": "male"}'
• response = requests.put(url1, data)
• response.text
• response.json()
47
Update, delete & post
• Updating
– requests.patch(url, data)
• Deleting
– requests.delete(url)
• Posting
– requests.post(url, data)
48
Requests API
• Requests for Python
– https://requests.readthedocs.io/en/latest/
49
Pretty printing
• import json
• print json.dumps(response.json(), indent=4)
{
"200": {
"age": 25,
"name": "David"
},
…
50
Roadmap
• Firebase REST API
• Firebase Javascript/Web API
– Useful for your project
51
52
Choose this for web app
53
Copy this &
replace the
firebaseConfig in
the sample html
file
54
Demo html page
val() returns a Javascript object
representing content of snapshot
55
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")
56
Modify the data in database
• Observe the data automatically changed in
the browser
57
Write data using set()
• function writeUserData(userId, name, email) {
firebase.database().ref("users/" + userId).set({
name: name,
email: email
});
Setting/overwriting the data of user 123
}
• writeUserData("123", "John", "[email protected]");
58
Write data using push() and set()
• firebase.database().ref("users").push().set({na
me: "John", email: "[email protected]"});
• push() will automatically generate a key
– In this case, id for the new user
• Which REST command is this similar to?
59
Update data
• function updateUserData(userId, phone) {
firebase.database().ref("users/"+userId).update({
phone: phone
});
} Note this does not remove other data of user 123
What if you replace "update" with "set"?
• updateUserData("123", "(626)123-0000");
60
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());
});
});
Press Ctrl+Shift+J in Chrome for console window
61
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
62
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());
});
});
63
Filtering data
• It also supports:
– orderByKey()
– orderByValue()
64
orderByValue() example
queryRef = firebase.database().ref("users/500/scores")
.orderByValue();
queryRef.on("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key + ": " + child.val());
});
});
65
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
66
Resources
• Firebase REST API
– https://firebase.google.com/docs/reference/rest/
database/
• Requests for Python
– https://requests.readthedocs.io/en/latest/
67
Resources
• Firebase Firestore Tutorial
– https://www.youtube.com/watch?v=4d-gIPGzmK4
– On how to develop a web app using Firestore
68