Winnie Mo
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ###### tags: `Computational Statistics` `API` `Opendata` # 如何利用API取得資料 在現在的研究上,很多都需要獲取大量的資料去做分析,因此習得一個可以獲取資料的技能是非常重要的。透過API,不管是國內外網站,都有自己的資料庫,所儲存的大量開放資料可以提供給使用者使用,但是**前提就是要知道該如何使用API。** --- 該篇是給跟我一樣會遇到需要大量不同種類資料的人而寫的。 講述內容***有兩大部分***。 - API是什麼? - 介紹幾個我本身已經用過的網站及步驟。 ==希望可以讓需要資料的人能夠輕易取得,並且在自己的研究上做出新的發現。== --- # API是什麼? API全名叫Application Programming Interface。 現今所使用的API,很多都是利用HTTP(HTTP, Hyper Text Transfer Protocol)當作媒介。 ![The concept of API](https://i.imgur.com/c1j1wnj.png) 透過上面示意圖來看。我們就是User、Client,而線上的資料庫網站即是Waiter也可當成Front end。User透過Menu(API)去點我們要的餐點亦即想取得之資料,再透過Waiter把我們點餐的訊息(Request)送去給廚房(Back end system、Database、Server),廚房把餐點準備好送出去(Response)。一連串的過程,透過API去進行,讓複雜的過程簡化,最終獲取我們要的資料。 ![The concept of API -2](https://i.imgur.com/BlNVrXg.png) 總結來說,整個架構主要有五部分: :::info 1. A client sends an HTTP request to the web. 2. A web server receives the request. 3. The server runs an application to process the request. 4. The server returns an HTTP response to the browser. 5. The client receives the response. ::: # 實做API - Hand on operation **==事實上大部分的網站步驟都大同小異,只要知道幾個大方向,相信很快就可以上手。==** 以下會介紹幾個我本身用過的網站。 ## 中央氣象局 Central Weather Bureau #### **Step 1** 註冊會員,登入後取得自己的API KEY。 [中央氣象局氣象會員登入網址](https://pweb.cwb.gov.tw/CWBMEMBER3/) ![註冊會員](https://i.imgur.com/6YZdPEy.png) :::warning 登入完成後,請點選<font color="#f00">紅色框框</font>進入到資料平台的網站,再次登入所註冊的中央氣象局帳號。 ::: ![登入完成](https://i.imgur.com/jXG02vI.png) ![登入](https://i.imgur.com/OUVk8Us.png) :::warning 按下取得授權碼就可以拿到API KEY。**每個人的API KEY都不一樣是專屬於自己的,所以不要洩漏自己的code給別人。** ::: ![API](https://i.imgur.com/rHGvu40.png) #### **Step 2** 選定資料 :::warning 根據資料主題,選擇你要的資料群。這邊是拿/觀測/自動氣象站-氣象 ::: ![](https://i.imgur.com/fhfnxGW.png) :::warning 點選畫面中的資料集選擇API,若要拿歷史資料則點選historyAPI。 ::: ![](https://i.imgur.com/ufinZy4.png) #### **Step 3** 點選API後,會導入到一個叫Swagger的網站,專門處理API。 > 若想知道更多詳細資訊,可點選[Swagger](https://swagger.io/) ![](https://i.imgur.com/EFEis2Y.png) :::warning 在觀測欄中,能夠看到有兩個藍色的GET,依照要的資料點選,可以看到裏頭有個Try it out。按下去後,就可以把自己的API KEY貼至Authorization。 ::: ![](https://i.imgur.com/mnkgokv.png) ![](https://i.imgur.com/7n6SIoa.png) #### **Step 4** 資料execute :::warning 根據上述把資料execute後,會得到如下面這張圖所示,即是json檔裡面的內容,這邊要注意的地方就是**Request URL,在後續程式裡面會使用到。** ::: ![](https://i.imgur.com/nA30Pnp.png) #### **Step 5** Coding - 利用python做後續處理。 - Import necessary packages ``` import requests import json import pandas as pd ``` - Configure api variables & Construct url ``` # assign the authorization code, data id, and the return format auth = 'CWB-xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx' dataset_id = 'O-A0001-001' data_format = 'json' data_url = f'https://opendata.cwb.gov.tw/fileapi/v1/opendataapi/{dataset_id}?Authorization={auth}&format={data_format}' data_url ``` :::warning 複製data_url,貼至網頁上,它就會自動幫你下載json檔。 ::: ![](https://i.imgur.com/2sWVsYT.png) - Make the call ``` response = requests.get(data_url) response.text ``` - Parse the respose with json module ``` data = json.loads(response.text) print(type(data)) data ``` :::warning 將上述的code執行完,根據Data中的資訊獲得你想要的,做後續的應用分析。 ::: ## ECMWF Re-Analysis Version 5 (ERA5) >該網站提供全球氣候之資訊,主要是大氣模式之模擬資料。利用即時天氣資料,透過相關公式去模擬未來的天氣。所擁有的數據解析為30km,使用 137 個級別解析大氣。若以地面起算,最高可達 80 公里。 [Website of ERA5 login interface](https://www.ecmwf.int/en/forecasts/datasets/reanalysis-datasets/era5) ![](https://i.imgur.com/gZcVCCd.png) 請點選<font color="#f00">紅色框框</font>進入到[ERA5的資料平台網站](https://cds.climate.copernicus.eu/cdsapp#!/home)。 > 有關下載ERA5開放資料,除了可以透過API,也可以在**網頁介面上**,手動勾選下載,依照自己喜歡的方式去獲取資料,以下則是介紹透過Python code,利用API取得資料。 ![](https://i.imgur.com/1XrTr4G.png) #### **Step 1** 註冊會員,登入後可以在自己的info找到API。 ![](https://i.imgur.com/DzI1KUC.png) :::warning 點選[How to use the CDS API](https://cds.climate.copernicus.eu/api-how-to),裡頭分別有Window/MacOS/Linux的詳細解說。 ::: #### **Step 2** 在本機端的C:\Users\xxx目錄底下新建一個名為.cdsapirc的檔案。 :::warning 先在目錄下新增一個.txt檔,利用notepad++,把圖片中用灰色長方形的兩行內容直接複製到.txt檔,而後儲存檔案,**並把檔案格式改成.cdsapirc**。 ![](https://i.imgur.com/QsZ1AbX.png) 若還是不能成功建立檔案的話,點選[How to download ERA5](https://confluence.ecmwf.int/display/CKB/How+to+download+ERA5#heading-3-DownloadingonlineERA5familydatathroughtheCDSwebinterface),有詳細說明該怎麼建立.cdsapirc。 ::: 若成功的話,可以看到有個名為.cdsapirc的檔案在目錄底下 ![](https://i.imgur.com/gb0mGxa.png) #### **Step 3** 開啟cmd,下載cdsapi module。 ``` pip install cdsapi ``` #### **Step 4** 在官網上找尋資料,並複製python code。 :::warning 點選**Datasets**,選擇你要的資料並download data. ![](https://i.imgur.com/25t13W4.png) ::: ![](https://i.imgur.com/0rP0mq1.png) :::warning 點選完資料的類型後,在**Download data**下將code直接copy+paste,貼去執行。下載好的資料可以在**Your requests**中找到。 ::: ![](https://i.imgur.com/Bb1xL3A.png) ![](https://i.imgur.com/RfqYVpt.png)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully