1. 程式人生 > >REST介紹與CURL應用

REST介紹與CURL應用

先大致瞭解RESTFull概念之後,再進行實際的curl操作:

1、 REST引言

越來越多的人開始意識到,網站即軟體,而且是一種新型的軟體。

這種”網際網路軟體”採用客戶端/伺服器模式,建立在分散式體系上,通過網際網路通訊,具有高延時(high latency)、高併發等特點。

RESTful架構,就是目前最流行的一種網際網路軟體架構。它結構清晰、符合標準、易於理解、擴充套件方便,所以正得到越來越多網站的採用。

1.1 名稱

REST,即Representational State Transfer的縮寫,”表現層狀態轉化”。如果一個架構符合REST原則,就稱它為RESTful架構。

1.2資源(Resources)

REST的名稱”表現層狀態轉化”中,省略了主語。”表現層”其實指的是”資源”(Resources)的”表現層”。所謂”資源”,就是網路上的一個實體,或者說是網路上的一個具體資訊。

1.3表現層(Representation)

“資源”是一種資訊實體,它可以有多種外在表現形式。我們把”資源”具體呈現出來的形式,叫做它的”表現層”(Representation)。

文字可以用txt格式表現,也可以用HTML格式、XML格式、JSON格式表現,甚至可以採用二進位制格式;圖片可以用JPG格式表現,也可以用PNG格式表現。

URI只代表資源的實體,不代表它的形式。嚴格地說,有些網址最後的”.html”字尾名是不必要的,因為這個字尾名錶示格式,屬於”表現層”範疇,而URI應該只代表”資源”的位置。它的具體表現形式,應該在HTTP請求的頭資訊中用Accept和Content-Type欄位指定,這兩個欄位才是對”表現層”的描述。

1.4狀態轉化(State Transfer)

網際網路通訊協議HTTP協議,是一個無狀態協議。這意味著,所有的狀態都儲存在伺服器端。因此,如果客戶端想要操作伺服器,必須通過某種手段,讓伺服器端發生”狀態轉化”(State Transfer)。而這種轉化是建立在表現層之上的,所以就是”表現層狀態轉化”。

客戶端用到的手段,只能是HTTP協議。具體來說,就是HTTP協議裡面,四個表示操作方式的動詞:GET、POST、PUT、DELETE。它們分別對應四種基本操作:
- GET用來獲取資源
- POST用來新建資源(也可以用於更新資源)
- PUT用來更新資源
- DELETE

用來刪除資源

1.5 小結

  • 每一個URI代表一種資源;
  • 客戶端和伺服器之間,傳遞這種資源的某種表現層;
  • 客戶端通過四個HTTP動詞,對伺服器端資源進行操作,實現”表現層狀態轉化”。

2、RESTful API

必須有一種統一的機制,方便不同的前端裝置與後端進行通訊。這導致API構架的流行。RESTful API是目前比較成熟的一套網際網路應用程式的API設計理論。

2.1 協議

API與使用者的通訊協議,總是使用HTTPs協議。
應該儘量將API部署在專用域名之下。
https://api.example.com

2.2 版本(Versioning)

應該將API的版本號放入URL。
ttps://api.example.com/v1/

2.3 路徑(Endpoint)

路徑又稱”終點”(endpoint),表示API的具體網址。

在RESTful架構中,每個網址代表一種資源(resource),所以網址中不能有動詞,只能有名詞,而且所用的名詞往往與資料庫的表格名對應。一般來說,資料庫中的表都是同種記錄的”集合”(collection),所以API中的名詞也應該使用複數。

舉例來說,有一個API提供動物園(zoo)的資訊,還包括各種動物和僱員的資訊,則它的路徑應該設計成下面這樣。

https://api.example.com/v1/zoos
https://api.example.com/v1/animals
https://api.example.com/v1/employees

2.4 HTTP動詞

對於資源的具體操作型別,由HTTP動詞表示。

常用的HTTP動詞有下面五個(括號裡是對應的SQL命令)。

  • GET(SELECT):從伺服器取出資源(一項或多項)。
  • POST(CREATE):在伺服器新建一個資源。
  • PUT(UPDATE):在伺服器更新資源(客戶端提供改變後的完整資源)。
  • PATCH(UPDATE):在伺服器更新資源(客戶端提供改變的屬性)。
  • DELETE(DELETE):從伺服器刪除資源。

還有兩個不常用的HTTP動詞。
- HEAD:獲取資源的元資料。
- OPTIONS:獲取資訊,關於資源的哪些屬性是客戶端可以改變的。

下面是一些例子。

GET /zoos:列出所有動物園
POST /zoos:新建一個動物園
GET /zoos/ID:獲取某個指定動物園的資訊
PUT /zoos/ID:更新某個指定動物園的資訊(提供該動物園的全部資訊)
PATCH /zoos/ID:更新某個指定動物園的資訊(提供該動物園的部分資訊)
DELETE /zoos/ID:刪除某個動物園
GET /zoos/ID/animals:列出某個指定動物園的所有動物
DELETE /zoos/ID/animals/ID:刪除某個指定動物園的指定動物

2.5 過濾資訊(Filtering)

如果記錄數量很多,伺服器不可能都將它們返回給使用者。API應該提供引數,過濾返回結果。

下面是一些常見的引數。

?limit=10:指定返回記錄的數量
?offset=10:指定返回記錄的開始位置。
?page=2&per_page=100:指定第幾頁,以及每頁的記錄數。
?sortby=name&order=asc:指定返回結果按照哪個屬性排序,以及排序順序。
?animal_type_id=1:指定篩選條件

引數的設計允許存在冗餘,即允許API路徑和URL引數偶爾有重複。比如,GET /zoo/ID/animals 與 GET /animals?zoo_id=ID 的含義是相同的。

2.6狀態碼(Status Codes)

伺服器向用戶返回的狀態碼和提示資訊,常見的有以下一些(方括號中是該狀態碼對應的HTTP動詞)。

200 OK - [GET]:伺服器成功返回使用者請求的資料,該操作是冪等的(Idempotent)。
201 CREATED - [POST/PUT/PATCH]:使用者新建或修改資料成功。
202 Accepted - [*]:表示一個請求已經進入後臺排隊(非同步任務)
204 NO CONTENT - [DELETE]:使用者刪除資料成功。
400 INVALID REQUEST - [POST/PUT/PATCH]:使用者發出的請求有錯誤,伺服器沒有進行新建或修改資料的操作,該操作是冪等的。
401 Unauthorized - [*]:表示使用者沒有許可權(令牌、使用者名稱、密碼錯誤)。
403 Forbidden - [*] 表示使用者得到授權(與401錯誤相對),但是訪問是被禁止的。
404 NOT FOUND - [*]:使用者發出的請求針對的是不存在的記錄,伺服器沒有進行操作,該操作是冪等的。
406 Not Acceptable - [GET]:使用者請求的格式不可得(比如使用者請求JSON格式,但是隻有XML格式)。
410 Gone -[GET]:使用者請求的資源被永久刪除,且不會再得到的。
422 Unprocesable entity - [POST/PUT/PATCH] 當建立一個物件時,發生一個驗證錯誤。
500 INTERNAL SERVER ERROR - [*]:伺服器發生錯誤,使用者將無法判斷髮出的請求是否成功。

2.7 錯誤處理(Error handling)

如果狀態碼是4xx,就應該向使用者返回出錯資訊。一般來說,返回的資訊中將error作為鍵名,出錯資訊作為鍵值即可。

    {
        error: "Invalid API key"
    }

2.8 返回結果

針對不同操作,伺服器向用戶返回的結果應該符合以下規範。

GET /collection:返回資源物件的列表(陣列)
GET /collection/resource:返回單個資源物件
POST /collection:返回新生成的資源物件
PUT /collection/resource:返回完整的資源物件
PATCH /collection/resource:返回完整的資源物件
DELETE /collection/resource:返回一個空文件

2.9 Hypermedia API

RESTful API最好做到Hypermedia,即返回結果中提供連結,連向其他API方法,使得使用者不查文件,也知道下一步應該做什麼。

比如,當用戶向api.example.com的根目錄發出請求,會得到這樣一個文件。


    {"link": {
      "rel":   "collection https://www.example.com/zoos",
      "href":  "https://api.example.com/zoos",
      "title": "List of zoos",
      "type":  "application/vnd.yourformat+json"
    }}

上面程式碼表示,文件中有一個link屬性,使用者讀取這個屬性就知道下一步該呼叫什麼API了。rel表示這個API與當前網址的關係(collection關係,並給出該collection的網址),href表示API的路徑,title表示API的標題,type表示返回型別。

3、curl

3.1 curl介紹

curl命令是一個功能強大的網路工具,它能夠通過http、ftp等方式下載檔案,也能夠上傳檔案。其實curl遠不止前面所說的那些功能

curl命令使用了libcurl庫來實現,libcurl庫常用在C程式中用來處理HTTP請求,curlpp是libcurl的一個C++封裝,這幾個東西可以用在抓取網頁、網路監控等方面的開發,而curl命令可以幫助來解決開發過程中遇到的問題。

安裝curl

[root@hadron ~]# yum install -y curl

3.2 curl所有引數概覽

[[email protected] ~]# curl --help
Usage: curl [options...] <url>
Options: (H) means HTTP/HTTPS only, (F) means FTP only
     --anyauth       Pick "any" authentication method (H)
 -a, --append        Append to target file when uploading (F/SFTP)
     --basic         Use HTTP Basic Authentication (H)
     --cacert FILE   CA certificate to verify peer against (SSL)
     --capath DIR    CA directory to verify peer against (SSL)
 -E, --cert CERT[:PASSWD] Client certificate file and password (SSL)
     --cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)
     --ciphers LIST  SSL ciphers to use (SSL)
     --compressed    Request compressed response (using deflate or gzip)
 -K, --config FILE   Specify which config file to read
     --connect-timeout SECONDS  Maximum time allowed for connection
 -C, --continue-at OFFSET  Resumed transfer offset
 -b, --cookie STRING/FILE  String or file to read cookies from (H)
 -c, --cookie-jar FILE  Write cookies to this file after operation (H)
     --create-dirs   Create necessary local directory hierarchy
     --crlf          Convert LF to CRLF in upload
     --crlfile FILE  Get a CRL list in PEM format from the given file
 -d, --data DATA     HTTP POST data (H)
     --data-ascii DATA  HTTP POST ASCII data (H)
     --data-binary DATA  HTTP POST binary data (H)
     --data-urlencode DATA  HTTP POST data url encoded (H)
     --delegation STRING GSS-API delegation permission
     --digest        Use HTTP Digest Authentication (H)
     --disable-eprt  Inhibit using EPRT or LPRT (F)
     --disable-epsv  Inhibit using EPSV (F)
 -D, --dump-header FILE  Write the headers to this file
     --egd-file FILE  EGD socket path for random data (SSL)
     --engine ENGINGE  Crypto engine (SSL). "--engine list" for list
 -f, --fail          Fail silently (no output at all) on HTTP errors (H)
 -F, --form CONTENT  Specify HTTP multipart POST data (H)
     --form-string STRING  Specify HTTP multipart POST data (H)
     --ftp-account DATA  Account data string (F)
     --ftp-alternative-to-user COMMAND  String to replace "USER [name]" (F)
     --ftp-create-dirs  Create the remote dirs if not present (F)
     --ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)
     --ftp-pasv      Use PASV/EPSV instead of PORT (F)
 -P, --ftp-port ADR  Use PORT with given address instead of PASV (F)
     --ftp-skip-pasv-ip Skip the IP address for PASV (F)
     --ftp-pret      Send PRET before PASV (for drftpd) (F)
     --ftp-ssl-ccc   Send CCC after authenticating (F)
     --ftp-ssl-ccc-mode ACTIVE/PASSIVE  Set CCC mode (F)
     --ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F)
 -G, --get           Send the -d data with a HTTP GET (H)
 -g, --globoff       Disable URL sequences and ranges using {} and []
 -H, --header LINE   Custom header to pass to server (H)
 -I, --head          Show document info only
 -h, --help          This help text
     --hostpubmd5 MD5  Hex encoded MD5 string of the host public key. (SSH)
 -0, --http1.0       Use HTTP 1.0 (H)
     --ignore-content-length  Ignore the HTTP Content-Length header
 -i, --include       Include protocol headers in the output (H/F)
 -k, --insecure      Allow connections to SSL sites without certs (H)
     --interface INTERFACE  Specify network interface/address to use
 -4, --ipv4          Resolve name to IPv4 address
 -6, --ipv6          Resolve name to IPv6 address
 -j, --junk-session-cookies Ignore session cookies read from file (H)
     --keepalive-time SECONDS  Interval between keepalive probes
     --key KEY       Private key file name (SSL/SSH)
     --key-type TYPE Private key file type (DER/PEM/ENG) (SSL)
     --krb LEVEL     Enable Kerberos with specified security level (F)
     --libcurl FILE  Dump libcurl equivalent code of this command line
     --limit-rate RATE  Limit transfer speed to this rate
 -l, --list-only     List only names of an FTP directory (F)
     --local-port RANGE  Force use of these local port numbers
 -L, --location      Follow redirects (H)
     --location-trusted like --location and send auth to other hosts (H)
 -M, --manual        Display the full manual
     --mail-from FROM  Mail from this address
     --mail-rcpt TO  Mail to this receiver(s)
     --mail-auth AUTH  Originator address of the original email
     --max-filesize BYTES  Maximum file size to download (H/F)
     --max-redirs NUM  Maximum number of redirects allowed (H)
 -m, --max-time SECONDS  Maximum time allowed for the transfer
     --metalink      Process given URLs as metalink XML file
     --negotiate     Use HTTP Negotiate Authentication (H)
 -n, --netrc         Must read .netrc for user name and password
     --netrc-optional Use either .netrc or URL; overrides -n
     --netrc-file FILE  Set up the netrc filename to use
 -N, --no-buffer     Disable buffering of the output stream
     --no-keepalive  Disable keepalive use on the connection
     --no-sessionid  Disable SSL session-ID reusing (SSL)
     --noproxy       List of hosts which do not use proxy
     --ntlm          Use HTTP NTLM authentication (H)
 -o, --output FILE   Write output to <file> instead of stdout
     --pass PASS     Pass phrase for the private key (SSL/SSH)
     --post301       Do not switch to GET after following a 301 redirect (H)
     --post302       Do not switch to GET after following a 302 redirect (H)
     --post303       Do not switch to GET after following a 303 redirect (H)
 -#, --progress-bar  Display transfer progress as a progress bar
     --proto PROTOCOLS  Enable/disable specified protocols
     --proto-redir PROTOCOLS  Enable/disable specified protocols on redirect
 -x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port
     --proxy-anyauth Pick "any" proxy authentication method (H)
     --proxy-basic   Use Basic authentication on the proxy (H)
     --proxy-digest  Use Digest authentication on the proxy (H)
     --proxy-negotiate Use Negotiate authentication on the proxy (H)
     --proxy-ntlm    Use NTLM authentication on the proxy (H)
 -U, --proxy-user USER[:PASSWORD]  Proxy user and password
     --proxy1.0 HOST[:PORT]  Use HTTP/1.0 proxy on given port
 -p, --proxytunnel   Operate through a HTTP proxy tunnel (using CONNECT)
     --pubkey KEY    Public key file name (SSH)
 -Q, --quote CMD     Send command(s) to server before transfer (F/SFTP)
     --random-file FILE  File for reading random data from (SSL)
 -r, --range RANGE   Retrieve only the bytes within a range
     --raw           Do HTTP "raw", without any transfer decoding (H)
 -e, --referer       Referer URL (H)
 -J, --remote-header-name Use the header-provided filename (H)
 -O, --remote-name   Write output to a file named as the remote file
     --remote-name-all Use the remote file name for all URLs
 -R, --remote-time   Set the remote file's time on the local output
 -X, --request COMMAND  Specify request command to use
     --resolve HOST:PORT:ADDRESS  Force resolve of HOST:PORT to ADDRESS
     --retry NUM   Retry request NUM times if transient problems occur
     --retry-delay SECONDS When retrying, wait this many seconds between each
     --retry-max-time SECONDS  Retry only within this period
 -S, --show-error    Show error. With -s, make curl show errors when they occur
 -s, --silent        Silent mode. Don't output anything
     --socks4 HOST[:PORT]  SOCKS4 proxy on given host + port
     --socks4a HOST[:PORT]  SOCKS4a proxy on given host + port
     --socks5 HOST[:PORT]  SOCKS5 proxy on given host + port
     --socks5-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy
     --socks5-gssapi-service NAME  SOCKS5 proxy service name for gssapi
     --socks5-gssapi-nec  Compatibility with NEC SOCKS5 server
 -Y, --speed-limit RATE  Stop transfers below speed-limit for 'speed-time' secs
 -y, --speed-time SECONDS  Time for trig speed-limit abort. Defaults to 30
     --ssl           Try SSL/TLS (FTP, IMAP, POP3, SMTP)
     --ssl-reqd      Require SSL/TLS (FTP, IMAP, POP3, SMTP)
 -2, --sslv2         Use SSLv2 (SSL)
 -3, --sslv3         Use SSLv3 (SSL)
     --ssl-allow-beast Allow security flaw to improve interop (SSL)
     --stderr FILE   Where to redirect stderr. - means stdout
     --tcp-nodelay   Use the TCP_NODELAY option
 -t, --telnet-option OPT=VAL  Set telnet option
     --tftp-blksize VALUE  Set TFTP BLKSIZE option (must be >512)
 -z, --time-cond TIME  Transfer based on a time condition
 -1, --tlsv1         Use => TLSv1 (SSL)
     --tlsv1.0       Use TLSv1.0 (SSL)
     --tlsv1.1       Use TLSv1.1 (SSL)
     --tlsv1.2       Use TLSv1.2 (SSL)
     --trace FILE    Write a debug trace to the given file
     --trace-ascii FILE  Like --trace but without the hex output
     --trace-time    Add time stamps to trace/verbose output
     --tr-encoding   Request compressed transfer encoding (H)
 -T, --upload-file FILE  Transfer FILE to destination
     --url URL       URL to work with
 -B, --use-ascii     Use ASCII/text transfer
 -u, --user USER[:PASSWORD]  Server user and password
     --tlsuser USER  TLS username
     --tlspassword STRING TLS password
     --tlsauthtype STRING  TLS authentication type (default SRP)
     --unix-socket FILE    Connect through this UNIX domain socket
 -A, --user-agent STRING  User-Agent to send to server (H)
 -v, --verbose       Make the operation more talkative
 -V, --version       Show version number and quit
 -w, --write-out FORMAT  What to output after completion
     --xattr        Store metadata in extended file attributes
 -q                 If used as the first parameter disables .curlrc

3.3 簡單應用

  1. 下載單個檔案,預設將輸出列印到標準輸出中(STDOUT)中
[[email protected] ~]# curl http://www.centos.org
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.1</center>
</body>
</html>
  1. 可以使用-o或-O重定向,抓取頁面內容到一個檔案中
[root@hadron ~]# curl -o home.html http://www.baidu.com
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2381  100  2381    0     0  37752      0 --:--:-- --:--:-- --:--:-- 38403
[root@hadron ~]# ll |grep home.html
-rw-r--r--  1 root root        2381 310 16:31 home.html

3.4 下載

-O(大寫的),後面的url要具體到某個檔案,不然抓不下來

-L選項進行強制重定向

[root@hadron ~]# curl -L -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.2.2.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 32.2M  100 32.2M    0     0  42035      0  0:13:24  0:13:24 --:--:-- 37582

3.5 -u 指定使用者名稱和密碼

[root@hadron ~]# curl -u admin:admin http://192.168.1.25:8080/api/v1/clusters
{
  "href" : "http://192.168.1.25:8080/api/v1/clusters",
  "items" : [
    {
      "href" : "http://192.168.1.25:8080/api/v1/clusters/cc",
      "Clusters" : {
        "cluster_name" : "cc",
        "version" : "HDP-2.5"
      }
    }
  ]
}[root@hadron ~]# 

3.6 GET查詢

預設curl使用GET方式請求資料,這種方式下直接通過URL傳遞資料

[root@hadron ~]# curl http://192.168.1.181:9200/_cluster/health?pretty
{
  "cluster_name" : "es",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 3,
  "number_of_data_nodes" : 3,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0
}

3.7 -X指定協議

還可以通過 -X 選項指定協議

[root@hadron ~]# curl -XGET http://192.168.1.181:9200/_cluster/health?pretty
{
  "cluster_name" : "es",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 3,
  "number_of_data_nodes" : 3,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0
}
[root@hadron ~]# 

GET方法只是查詢,不改變系統狀態。
POST方法可以更改系統狀態

查詢節點的狀態

[root@hadron ~]# curl -XGET 192.168.1.181:9200/_nodes/process
{"_nodes":{"total":3,"successful":3,"failed":0},"cluster_name":"es","nodes":{"mWFZ25DdT-SbrP8fwu3NYg":{"name":"vnode1","transport_address":"192.168.1.181:9300","host":"vnode1","ip":"192.168.1.181","version":"5.1.1","build_hash":"5395e21","roles":["master","data","ingest"],"attributes":{"rack":"rack01"},"process":{"refresh_interval_in_millis":1000,"id":13073,"mlockall":true}},"xpPLpbXhSzOm3M-IfKhWfA":{"name":"vnode3","transport_address":"192.168.1.183:9300","host":"vnode3","ip":"192.168.1.183","version":"5.1.1","build_hash":"5395e21","roles":["master","data","ingest"],"attributes":{"rack":"rack01"},"process":{"refresh_interval_in_millis":1000,"id":91860,"mlockall":true}},"E0fwSa_qRSu_Ri0xjJn7bA":{"name":"vnode2","transport_address":"192.168.1.182:9300","host":"vnode2","ip":"192.168.1.182","version":"5.1.1","build_hash":"5395e21","roles":["master","data","ingest"],"attributes":{"rack":"rack01"},"process":{"refresh_interval_in_millis":1000,"id":15562,"mlockall":true}}}}

3.8 -d 傳遞資料

可以通過 –data/-d 方式指定使用POST方式傳遞資料

建立(PUT)

[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/32' -d '{ "empname": "emp32"}'
{"_index":"dept","_type":"employee","_id":"32","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"created":true}

注意cURL命令的一個新選項: -d 引數。
此選項的值是將作為請求負載的文字,也即請求主
體(request body)。這樣,我們可以傳送附加資訊,如文件定義。同時,注意唯一識別符號(32)是
放在URL,而不是請求主體中。

[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/1' -d '{ "empname": "emp1"}'
{"_index":"dept","_type":"employee","_id":"1","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"created":true}

[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/2' -d '{ "empname": "emp2"}'
{