Tuesday, October 3, 2017

curl, netcat, API testing

最近常常在測試一些同事寫的 API ,整理了一下自己覺得好用的小技巧:
(1) mock server
有時候想要看一下,自己生成的 curl 到底是產生怎麼樣的 http request ,產生怎樣的 body ,就需要先架一個簡單的 mock server 。

#如果需要看 http POST 會需要用 netcat
sudo nc -l 8000     #開啟一個 8000 port 的 tcp listener
# Python v2.7
python -m SimpleHTTPServer
# Python 3
python -m http.server 8000

(2) 快速生成 curl 指令
如果是對於既有的 web application 的話,可以利用 chrome 來取得。
Ctrl + Shift + i -> Network -> Copy as cURL 

(3) curl 常用的參數
-s  =>  silent, quiet mode 
-d =>  用來指定要放進 http request 的 body 的內容。
           用了 -d 選項之後,預設的 Content-Type 是 application/x-www-form-urlencoded
           如果要使用客制化的選項的話,要再加上 -H 參數。
-F =>  用了 -F 選項之後,預設的 Content-Type 是 multipart/form-data
           這個選項通常是用於「大量的資料」或是 binary data
-H => 用來指定 http  header 。常見的用法有:
           指定客戶端送出的資料格式                          -H 'Content-Type: application/json'
           告訴伺服器「客戶端想接受的資料格式」  -H 'Accept: application/json'

(4) 從 server side 的 source code 來理解
常見的 server side framework 可以處理的 http content type 通常是下列四種:
  • application/json
  • application/xml
  • application/x-www-form-urlencoded
  • multipart/form-data
(5) 由 server side 的 source code 來猜測, client side 的 curl 該如何產生?
若 server side 是用類似 parseForm, formValue 之類的函數來處理。curl 會是如下的形式:

curl -d 'title=標題&content=測試'  http://localhost:8000/