Lecture 2 - Firebase rest & web api
Lecture 2 - Firebase rest & 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
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
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"
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
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
21
Check syntax of JSON
• JSON validator
– http://jsonlint.com/
22
Roadmap
• Firebase REST API
23
curl
• Command line tool for data transfer
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"}
28
PUT
• curl -X PUT 'https://inf551-
1b578.firebaseio.com/weather.json' -d '"hot"'
– "hot"
29
PUT
• curl -X PUT 'https://inf551-
1b578.firebaseio.com/users/100.json' -d
'{"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'
31
POST
• curl -X POST -d '{"name": "John"}'
'https://inf551-
1b578.firebaseio.com/users.json'
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'
33
DELETE
• curl -X DELETE 'https://inf551-
1b578.firebaseio.com/users/100.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’
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'
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
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'
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
{
"200": {
"age": 25,
"name": "David"
},
…
50
Roadmap
• Firebase REST API
51
52
Choose this for web app
53
Copy this &
replace the
firebaseConfig in
the sample html
file
54
Demo html page
55
Database reference
• firebase.database() returns a reference to the
firebase database as specified by
"firebaseConfig"
56
Modify the data in database
• Observe the data automatically changed in
the browser
57
Write data using set()
58
Write data using push() and set()
• firebase.database().ref("users").push().set({na
me: "John", email: "[email protected]"});
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
67
Resources
• Firebase Firestore Tutorial
– https://www.youtube.com/watch?v=4d-gIPGzmK4
– On how to develop a web app using Firestore
68