Firebase rest & web api

Firebase 概述(BaaS)

Firebase谷歌的一款应用后台服务。借助Firebase,应用开发者们可以快速搭建应用后台。

产品

  1. Firebase (realtime) database: Manage JSON documents + Real-time syncing data between users and devices
  2. Firebase (cloud) storage: Store images, photos, videos
  3. Firebase (user) authentication: Support sign in using Google, Facebook

使用

  1. Create a Firebase account: first use Google account,then go to Firebase console: https://console.firebase.google.com/
  2. Click on “Add project” to create a Firebase project
  3. Add Firebase to your web app
  4. any other interesting operation …

关于 Realtime database

  • Data in JSON(Javascript Object Notation) format JSON-review
  • When creating a real-time database, we should open up the access to allow us to read and write the data.
  • There are some difference between storing style from JSON file and Firebase real-time database
    1. JSON文件中的array元素在Realtime database下以object的形式存在,object对应的key为数组元素的索引
    2. JSON文件可以保存value为null的键值对,Realtime database则会忽略这一对键值对

Firebase REST API

关于RESTful API

REST:Representation State Transfer,表现层状态转移
一句话解释的话就是:通过URL定位资源,用HTTP动词(GET, POST, PUT, DELETE)描述操作从而用来实现前后端数据传输的协议。

命令行进行http数据传输:curl

For command operation, it’s convenient to use curl (Command line tool for data transfer)
curl详细使用:https://itbilu.com/linux/man/4yZ9qH_7X.html
注意,curl大小写敏感,请求的命令参数均为大写字符

curl例子 - CRUD

PUT & POST (C), GET (R), PATCH (U) ,DELETE (D)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
JSON tree:
{
"firstName": "John",
"lastName": "Smith",
"isMarried": false,
"age": 25,
"height_cm": 167.6,
"address": {
"streetAddress": "22nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567",
"xyz": null
}
],
"children": [],
"spouse": null,
"scores": [8.5, 9, 7, 10]
}

GET: get the specific resource

1
2
3
4
5
$ curl -X GET 'https://rest-apidemo.firebaseio.com/address/city.json'   return: "New York"%  
-X 可以省略 直接 curl GET url; GET 可以省略 直接 curl url

$ curl 'https://rest-apidemo.firebaseio.com/phoneNumbers/0.json' #refer to arr element by index
return:{"number":"212 555-1234","type":"home"}%

PUT: write a given value (e.g., “Mary”) to a specify node (e.g., “spouse”)

1
2
3
4
5
6
7
8
9
Add if node not exists (could add embedded nodes) - 添加数据
Overwrite if node already has value - 重写数据

$ curl -X PUT 'https://rest-apidemo.firebaseio.com/spouse.json' -d '"Mary"' # 注意引号

#This will add a new node "country" (assuming it does not exist yet)
#and a child of this node with key "province" and content: {"name": "Anhui"}
$ curl -X PUT 'https://rest-apidemo.firebaseio.com/country/province.json' -d '{"name": "Anhui"}'
$ curl -X PUT 'https://rest-apidemo.firebaseio.com/country.json' -d '{"province": {"name": "Anhui"}}'

POST: add new value to a given node

1
2
3
4
5
Automatically generates a new key & then stores the value for the new key
由于对于添加的数据,其自动生成一个key,所以保证不会重写数据(In contrast, PUT will simply overwrite the key)

$ curl -X POST 'https://rest-apidemo.firebaseio.com/country.json' -d '{"province": {"name": "Anhui"}}'
$ curl -X POST 'https://rest-apidemo.firebaseio.com/country.json' -d '"Anhui"'

PATCH: upsert a value to a given node

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Performs the update if value already exists  -更新节点
Otherwise, it inserts the new value -插入新节点
PATCH本质上是一个深度搜索符合节点的条件进行更新或者添加)

curl -X PATCH 'https://rest-apidemo.firebaseio.com/country.json' -d '{"province": {"name": "Hubei"}}'


好处:相比于PUT(对于已经存在的节点进行全局的修改),本质上来说PATCH实现的是对该节点的局部更新
注意:当需要更新的节点没有子节点(仅仅是一个key-value格式),无法使用PATCH,因为 -d 参数后需要传入键值对的格式
curl -X PATCH 'https://rest-apidemo.firebaseio.com/spouse.json' -d '"Sam"' # fail
{
"error" : "Invalid data; couldn't parse JSON object. Are you sending a JSON object with valid key names?"
}
curl -X PUT 'https://rest-apidemo.firebaseio.com/spouse.json' -d '"Sam"' # success

DELETE: delete a node

1
curl -X DELETE 'https://rest-apidemo.firebaseio.com/spouse.json'

从数据增加、减少上对PUT、PATCH和POST进行比较

PUT可能造成数据的增加(添加新节点下的value)和减少(overwrite整个节点导致其内嵌的节点被删除);
PATCH可能造成数据的增加(添加新节点下的value)和减少(update节点的用更少的数据去取代原先的数据)
POST一定会造成数据的增加(因为会自动加上key);

data querying by RESful API

  • orderBy=”$key”
  • orderBy=”
  • orderBy=”$value” 需要在Realtime database的Rules先声明
  • startAt/endAt
  • equalTo
  • limitToFirst/limitToLast

Specified in database rules:
https://firebase.google.com/docs/database/security/indexing-data

1
2
3
4
5
6
curl -X GET 'https://rest-apidemo.firebaseio.com/scores.json?orderBy="$key"&equalTo="1"'
curl -X GET 'https://rest-apidemo.firebaseio.com/scores.json?orderBy="$key"&startAt="1"'
curl -X GET 'https://rest-apidemo.firebaseio.com/scores.json?orderBy="$value"'

Orders ascendingly:
null -> false ->true -> number -> string -> object

REST API in Python

1
2
3
4
5
6
7
8
9
10
import requests

url = 'xxxx'
data = 'xxx'

requests.get(url)
requests.put(url, data)
requests.patch(url, data)
requests.delete(url)
requests.post(url, data)

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!