1. 程式人生 > >請求需要認證的API資料

請求需要認證的API資料

Go語言獲取需要許可權認證的API資料

公開API

首先看一個請求json資料的例子,一個公開的API,誰都可以訪問,無需許可權認證,
資料來源:https://api.coinmarketcap.com/v2/ticker/


接下來看如何請求需要許可權認證的API資料,資料來源為以下網址,
https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest
https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest
這兩個API是需要許可權認證的,也就是需要APIkey,沒有許可權的時候,你直接點選這兩個網址,返回的資料是這樣的,

{
    "status": {
        "timestamp": "2018-12-11T00:53:33.535Z",
        "error_code": 401,
        "error_message": "API key missing.",
        "elapsed": 0,
        "credit_count": 0
    }
}

也就是返回了錯誤,錯誤資訊為"API key missing."API祕鑰缺失。
到這個網站https://coinmarketcap.com/註冊一個賬號,就可以免費申請一個APIkey,接下來就可以用申請到的APIkey去正常獲取上面兩個網址的資料,通過許可權認證以後獲取到的資料是這樣的,

{
    "status": {
        "timestamp": "2018-12-11T00:42:59.418Z",
        "error_code": 0,
        "error_message": null,
        "elapsed": 9,
        "credit_count": 1
    },
    "data": [
        {
            "id": 1,
            "name": "Bitcoin",
            "symbol": "BTC",
            "slug"
: "bitcoin", "circulating_supply": 17416675, "total_supply": 17416675, "max_supply": 21000000, "date_added": "2013-04-28T00:00:00.000Z", "num_market_pairs": 6684, "tags": [ "mineable" ], "platform": null, "cmc_rank": 1, "last_updated": "2018-12-11T00:41:22.000Z", "quote": { "USD": { "price": 3490.26054654, "volume_24h": 4958844740.50419, "percent_change_1h": -0.352116, "percent_change_24h": -3.79482, "percent_change_7d": -10.3529, "market_cap": 60788733604.40956, "last_updated": "2018-12-11T00:41:22.000Z" } } }, { "id": 52, "name": "XRP", "symbol": "XRP", "slug": "ripple", ………………………………………底下資料省略…………………………………………

接下來就來看一下如何獲取這種需要許可權認證的API資料,下面以Go語言舉栗子,首先到官網檢視API文件,https://coinmarketcap.com/api/documentation/v1/#,如何請求API資料已經寫得很清楚,不過具體的每種語言的操作步驟不太一樣
在這裡插入圖片描述
看看Go語言要怎麼做,其實就是當你發起一個數據請求的時候要把你的APIkey新增到請求頭中,然後這個網站就知道你是有許可權的,就會給你正確的資料。

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

var (
	url   = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
	url1  = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info/"
	url2  = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest"
	mykey = "860da129-69ed-189a-9379-2d48a4c00bd6"
)

func main() {
	//首先建立一個客戶端client,
	client := &http.Client{}
	//建立一個請求request,
	reqest, err := http.NewRequest("GET", url, nil)
	//為請求頭新增祕鑰認證,
	reqest.Header.Set("X-CMC_PRO_API_KEY", mykey)
	//reqest.Header.Add("Accept", "application/json")
	//reqest.Header.Add("Accept-Encoding", "deflate")
	if err != nil {
		fmt.Println(err)
	}
	//執行請求,得到響應資料response,
	resp, err := client.Do(reqest)
	defer resp.Body.Close()
	//讀取響應體response的body,用`ioutil.ReadAll`讀取,該函式返回結果為byte,
	body, err := ioutil.ReadAll(resp.Body)
	//將byte轉為可讀取的string型別,列印一下,就會看到得到了正確的響應,
	fmt.Println(string(body))
}

執行結果

{
    "status": {
        "timestamp": "2018-12-11T01:13:02.768Z",
        "error_code": 0,
        "error_message": null,
        "elapsed": 10,
        "credit_count": 1
    },
    "data": [
        {
            "id": 1,
            "name": "Bitcoin",
            "symbol": "BTC",
            "slug": "bitcoin",
            "circulating_supply": 17416725,
            "total_supply": 17416725,
            "max_supply": 21000000,
            "date_added": "2013-04-28T00:00:00.000Z",
            "num_market_pairs": 6684,
            "tags": [
                "mineable"
            ],
            "platform": null,
            "cmc_rank": 1,
            "last_updated": "2018-12-11T01:11:20.000Z",
            "quote": {
                "USD": {
                    "price": 3477.56550428,
                    "volume_24h": 4902670930.10955,
                    "percent_change_1h": -0.418618,
                    "percent_change_24h": -4.16081,
                    "percent_change_7d": -10.7638,
                    "market_cap": 60567802057.53108,
                    "last_updated": "2018-12-11T01:11:20.000Z"
                }
            }
        },
        {
            "id": 52,
            "name": "XRP",
            "symbol": "XRP",
            …………………略………………………………
            …………………略………………………………
            …………………略………………………………

這裡最後的得到的最終資料是body,型別為byte,實際開發中,還需要將byte轉為結構體,才可以應用,至於如何將byte資料轉為結構體,可參考這篇文章Go語言如何解析複雜json資料