Tag: API

  • httr2: 3 ขั้นตอนในการทำงานกับข้อมูลบนเว็บด้วยภาษา R — ตัวอย่างการทำงานกับ Fake Store API

    httr2: 3 ขั้นตอนในการทำงานกับข้อมูลบนเว็บด้วยภาษา R — ตัวอย่างการทำงานกับ Fake Store API

    httr2 (อ่านว่า “hitter 2”) เป็น API (application programming interface) package ในภาษา R เพื่อทำงานกับข้อมูลที่อยู่บนอินเทอร์เน็ต อย่างข้อมูลบนหน้าเว็บไซต์ต่าง ๆ เป็นต้น

    ในบทความนี้ เราจะมาลองดูวิธีใช้ httr2 ผ่านการทำงานกับ Fake Store API ซึ่งมีข้อมูลจำลองของร้านค้าออนไลน์กัน

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 🏪 Install & Load httr2
    2. 💻 Working With API in 3 Steps
    3. ✍️ Step 1. Build Request
    4. 📨 Step 2. Send Request
    5. 🧑‍💻 Step 3. Interact With Response
      1. 📋 Check Content Type
      2. 📥 Get Body
      3. 👀 View Data
    6. 📬 POST, PATCH, DELETE
    7. 😺 GitHub
    8. 📃 References
    9. ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    🏪 Install & Load httr2

    ในการใช้งาน httr2 เราจะต้องไม่ลืมติดตั้งและโหลด package ก่อนแบบนี้:

    # Install httr2
    install.packages("httr2")
    
    # Library httr2
    library(httr2)
    

    💻 Working With API in 3 Steps

    การใช้งาน httr2 มีอยู่ 3 ขั้นตอน ได้แก่:

    1. Build request: สร้าง request ที่จะส่ง
    2. Send request: ส่ง request ไปยังปลายทาง
    3. Interact with response: ทำงานกับข้อมูลที่ได้รับ

    เราลองไปดูทั้ง 3 ขั้นตอนจากตัวอย่างการดึงข้อมูล products (GET) จาก Fake Store API กัน


    ✍️ Step 1. Build Request

    ในขั้นแรก เราจะสร้าง request ที่เราจะส่งให้กับ Fake Store API:

    1. กำหนด base URL ของ Fake Store API
    2. สร้าง request ด้วย request()
    3. เพิ่ม endpoint ใน URL ด้วย req_url_path_append()
    # Define base URL
    base_url <- "<https://fakestoreapi.com>"
    
    # Build a request
    get_req <- request(base_url) |>
      
      # Add endpoint
      req_url_path_append("products")
    

    ในขั้นนี้ request จะยังไม่ถูกส่งออกไป และเราสามารถทดสอบ request ได้ด้วย req_dry_run():

    # Dry run the request
    get_req |> req_dry_run()
    

    ผลลัพธ์:

    GET /products HTTP/1.1
    accept: */*
    accept-encoding: deflate, gzip
    host: fakestoreapi.com
    user-agent: httr2/1.1.2 r-curl/6.4.0 libcurl/8.14.1
    

    📨 Step 2. Send Request

    เมื่อเราพอใจกับผลทดสอบ เราสามารถส่ง request ออกไปได้ด้วย req_perform():

    # Perform the request
    get_resp <- get_req |> req_perform()
    

    เราสามารถเช็กสถานะของ response ได้ด้วย resp_status():

    # View response status
    get_resp |> resp_status()
    

    ผลลัพธ์:

    200
    

    ซึ่งแสดงให้เห็นว่า request ของเราส่ง response กลับมาได้สำเร็จ


    🧑‍💻 Step 3. Interact With Response

    ในขั้นสุดท้าย เราจะสำรวจ response ที่ได้กลับมากัน:

    1. Check content type: เช็กประเภทข้อมูล
    2. Get body: ดึงข้อมูลจาก response
    3. View data: ดูตัวอย่างข้อมูล

    .

    📋 Check Content Type

    เราสามารถเช็กประเภทข้อมูลใน response ได้ด้วย resp_content_type():

    # Check the response content type
    get_resp |> resp_content_type()
    

    ผลลัพธ์:

    "application/json"
    

    ซึ่งแสดงให้เห็นว่า สิ่งที่ได้รับกลับมาอยู่ในรูปแบบ JSON

    .

    📥 Get Body

    จากนั้น เราสามารถดึงข้อมูลจาก response ได้ด้วย resp_body_*() เช่น:

    • resp_body_html(): ดึงข้อมูลที่เป็น HTML
    • resp_body_xml(): ดึงข้อมูลที่เป็น XML
    • resp_body_json(): ดึงข้อมูลที่เป็น JSON

    อย่างในตัวอย่าง เราจะดึงข้อมูลด้วย resp_body_json() เพราะข้อมูลของเราเป็น JSON:

    # Extract the content
    products <- get_resp |> resp_body_json()
    

    .

    👀 View Data

    สุดท้าย เราสามารถดูตัวอย่างข้อมูลได้ด้วย head():

    # View the first entry
    head(products, n = 1)
    

    ผลลัพธ์:

    [[1]]
    [[1]]$id
    [1] 1
    
    [[1]]$title
    [1] "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops"
    
    [[1]]$price
    [1] 109.95
    
    [[1]]$description
    [1] "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday"
    
    [[1]]$category
    [1] "men's clothing"
    
    [[1]]$image
    [1] "<https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg>"
    
    [[1]]$rating
    [[1]]$rating$rate
    [1] 3.9
    
    [[1]]$rating$count
    [1] 120
    

    📬 POST, PATCH, DELETE

    จากตัวอย่าง เราจะเห็นได้ว่า functions ของ httr2 แบ่งเป็น 2 กลุ่ม ได้แก่:

    1. req_*() ซึ่งใช้กับ request
    2. resp_*() ซึ่งใช้กับ response

    นอกจาก functions ที่เราได้เห็นก่อนหน้านี้ httr2 ยังมี functions อื่นที่ให้เรียกใช้งานได้ เช่น:

    • req_method(): เปลี่ยน method ของ request
    • req_body_json(): เปลี่ยน body ของ request

    ยกตัวอย่างเช่น เราต้องการเปลี่ยน method เป็น POST เพื่อสร้าง product ใหม่บนหน้าเว็บ เราสามารถใช้ req_method() และ req_body_json() ได้แบบนี้:

    # Build a request
    post_req <- request(base_url) |>
      
      # Add endpoint
      req_url_path_append("products") |>
      
      # Change method to POST
      req_method("POST") |>
      
      # Add body
      req_body_json(list(
        title = "Summer Sunglasses",
        price = 29.99,
        description = "One pair for all summers.",
        image = "<https://unsplash.com/photos/sunglasses-beside-a-purse-LJqRUWr9V0w>",
        category = "Accessory"
        ))
    
    

    หรือ PATCH เพื่ออัปเดตข้อมูล product:

    # Build a request
    patch_req <- request(base_url) |>
      
      # Add endpoint
      req_url_path_append("products/1001") |>
      
      # Change method to PATCH
      req_method("PATCH") |>
      
      # Add body
      req_body_json(list(
        price = 59.99,
        description = "Limited edition: One pair for all summers."
      ))
    

    หรือ DELETE เพื่อลบ product ออก:

    # Build a request
    delete_req <- request(base_url) |>
      
      # Add endpoint
      req_url_path_append("products/1001") |>
      
      # Change method to DELETE
      req_method("DELETE")
    

    เป็นต้น

    สำหรับคนที่สนใจ สามารถศึกษา functions อื่น ๆ ของ httr2 เพิ่มเติมได้ที่ บทความ official ของ httr2


    😺 GitHub

    ดูตัวอย่าง code ทั้งหมดได้ที่ GitHub


    📃 References


    ✅ R Book for Psychologists: หนังสือภาษา R สำหรับนักจิตวิทยา

    📕 ขอฝากหนังสือเล่มแรกในชีวิตด้วยนะครับ 😆

    🙋 ใครที่กำลังเรียนจิตวิทยาหรือทำงานสายจิตวิทยา และเบื่อที่ต้องใช้ software ราคาแพงอย่าง SPSS และ Excel เพื่อทำข้อมูล

    💪 ผมขอแนะนำ R Book for Psychologists หนังสือสอนใช้ภาษา R เพื่อการวิเคราะห์ข้อมูลทางจิตวิทยา ที่เขียนมาเพื่อนักจิตวิทยาที่ไม่เคยมีประสบการณ์เขียน code มาก่อน

    ในหนังสือ เราจะปูพื้นฐานภาษา R และพาไปดูวิธีวิเคราะห์สถิติที่ใช้บ่อยกัน เช่น:

    • Correlation
    • t-tests
    • ANOVA
    • Reliability
    • Factor analysis

    🚀 เมื่ออ่านและทำตามตัวอย่างใน R Book for Psychologists ทุกคนจะไม่ต้องพึง SPSS และ Excel ในการทำงานอีกต่อไป และสามารถวิเคราะห์ข้อมูลด้วยตัวเองได้ด้วยความมั่นใจ

    แล้วทุกคนจะแปลกใจว่า ทำไมภาษา R ง่ายขนาดนี้ 🙂‍↕️

    👉 สนใจดูรายละเอียดหนังสือได้ที่ meb:

  • 4 ขั้นตอนในการใช้ google-genai library เพื่อทำงานกับ Gemini API — ตัวอย่างการสร้างสูตรอาหารที่ไม่เหมือนใคร

    4 ขั้นตอนในการใช้ google-genai library เพื่อทำงานกับ Gemini API — ตัวอย่างการสร้างสูตรอาหารที่ไม่เหมือนใคร

    ในบทความนี้ เราจะมาดู 4 ขั้นตอนในการใช้งาน google-genai ซึ่งเป็น official library สำหรับทำงานกับ Gemini API ผ่านตัวอย่างการสร้างสูตรอาหารใน Google Colab กัน:

    1. Import packages
    2. Create client
    3. Create function
    4. Generate response

    ถ้าพร้อมแล้ว ไปเริ่มกันเลย


    1. 📦 Import Packages
    2. 🧑‍💼 Create Client
    3. 📲 Create Function
    4. 📬 Generate Response
      1. 🤖 Set Model
      2. 🧑‍💻 Set User Prompt
      3. 🛠️ Set Configuration
      4. 📖 Generate Response
      5. 🖨️ Print Response
    5. 😺 Google Colab
    6. 📃 References

    📦 Import Packages

    เริ่มแรก เราจะ import 4 packages ที่จำเป็น ได้แก่:

    FromFunction/ClassFor
    googlegenaiทำงานกับ Gemini API
    google.genai.typesGenerateContentConfigตั้งค่า Gemini
    google.colabuserdataเรียก API key จากเมนู Secrets ใน Google Colab
    pydanticBaseModelกำหนดโครงสร้างของ response จาก Gemini
    # Import packages
    
    # google-genai library
    from google import genai
    from google.genai.types import GenerateContentConfig
    
    # Secret key
    from google.colab import userdata
    
    # pydantic
    from pydantic import BaseModel
    

    🧑‍💼 Create Client

    ในขั้นที่ 2 เราจะสร้าง client สำหรับทำงานกับ Gemini API

    เพื่อความปลอดภัย เราจะเก็บ API key ไว้ในเมนู Secrets ของ Google Colab

    เราสามารถเพิ่ม API key ด้วยการ import ผ่านปุ่ม “Gemini API keys” หรือผ่านการเพิ่ม API key เองด้วยปุ่ม “Add new secret”:

    หลังสร้าง API key ใน Secrets แล้ว เราสามารถเรียกใช้ API key ได้ด้วย userdata.get() ซึ่งต้องการ 1 argument คือ ชื่อ secret:

    # Get API key
    my_api = userdata.get("GOOGLE_API_KEY")
    

    จากนั้น เราจะสร้าง client ด้วย genai.Client() ซึ่งต้องการ 1 argument คือ API key:

    # Create client
    client = genai.Client(api_key=my_api)
    

    Note:

    • ในกรณีที่เราไม่ห่วงความปลอดภัยของ API key เราสามารถใส่ API key ใน genai.Client() ได้โดยตรง เช่น genai.Client(api_key="g04821...")
    • เราสามารถสร้าง API key ได้ฟรี โดยไปที่ Google AI Studio และกด “Create API key”

    📲 Create Function

    ในขั้นที่ 3 เราจะสร้าง function สำหรับเรียกใช้ Gemini ซึ่งต้องการ 3 arguments:

    1. model: Gemini model ที่เราจะเรียกใช้
    2. user_prompt: กำหนด user prompt
    3. config: กำหนดการตั้งค่าต่าง ๆ ของ model

    โดยทั้ง 3 arguments จะอยู่ใน client.models.generate_content():

    # Create a function to get Gemini response
    def get_response(model, user_prompt, config):
    
        # Get response
        response = client.models.generate_content(
    
            # Set model
            model=model,
    
            # Set user prompt
            contents=user_prompt,
    
            # Set config
            config=config
        )
    
        # Return response
        return response.text
    

    📬 Generate Response

    ในขั้นที่ 4 เราจะ get response จาก Gemini โดยใช้ function ที่เราสร้างในขั้นที่ 3

    เนื่องจาก function ต้องการ 3 arguments เราจะต้องกำหนด 3 สิ่งนี้ก่อนที่จะสร้าง response ได้:

    1. Model
    2. User prompt
    3. Configuration

    .

    🤖 Set Model

    ในตัวอย่างนี้ เราจะใช้ model เป็น Gemini 2.5 Flash ซึ่งเราสามารถกำหนดได้ดังนี้:

    # Set model
    gemini_model = "gemini-2.5-flash"
    

    Note: ดูชื่อ model อื่น ๆ ได้ที่ Gemini Models

    .

    🧑‍💻 Set User Prompt

    สำหรับ user prompt เราสามารถกำหนดเป็น string ได้แบบนี้:

    # Set user prompt
    gemini_user_prompt = """
    Create a healthy Thai-inspired burger for one person.
    
    Protein: chicken or tofu
    Bun: whole-wheat if possible (or lettuce wrap)
    
    Deliver (match field names exactly):
    - `menu` (string)
    - `ingredient` (list of items with name, description, amount, unit)
    - `steps` (30-word strings)
    - `calorie_kcal` (float, total for the dish)
    """
    

    .

    🛠️ Set Configuration

    สำหรับ configuration เราสามารถตั้งค่า model ได้หลายค่า

    ในตัวอย่างนี้ เราจะเลือกกำหนด 3 ค่า ได้แก่:

    1. System prompt
    2. Temperature
    3. Output type and structure

    ค่าที่ 1. System prompt คือ prompt ที่กำหนดพฤติกรรมของ Gemini ในการตอบสนองต่อ user prompt ของเรา

    เราสามารถกำหนด system prompt เป็น string ได้แบบนี้:

    # Set system prompt
    system_prompt = """
    You are a highly experienced home cook specialising in healthy Thai-style food.
    
    Constraints:
    - Single-serving
    - Favour grilling/pan-searing over deep-frying
    - Keep ingredients common in Thai kitchens
    - Keep steps <=7
    - Include an approximate total calories for the whole dish
    - Keep language simple
    - Return JSON only that matches the given schema exactly (no extra fields)
    """
    

    ค่าที่ 2. Temperature มีค่าระหว่าง 0 และ 2 โดย:

    • 0 จะทำให้ response ตายตัว (deterministic) มากขึ้น
    • 2 จะทำให้ response สร้างสรรค์ (creative) มากขึ้น

    Note: ค่า default ของ temperature อยู่ที่ 1 (Generate content with the Gemini API in Vertex AI)

    ในตัวอย่าง เราจะกำหนด temperature เป็น 2 เพื่อให้ response มีความสร้างสรรค์สูงสุด:

    # Set temperature
    temp = 2
    

    ค่าที่ 3. สำหรับ output type และ structure เราจะกำหนดดังนี้:

    กำหนด type เป็น "application/json" เพื่อให้ response อยู่ในรูป JSON object:

    # Set output type
    output_type = "application/json"
    

    Note: ดู type อื่น ๆ ได้ที่ Structured output

    กำหนดโครงสร้างของ JSON object ด้วย class และ BaseModel:

    # Set output structure
    class Ingredient(BaseModel):
        name: str
        description: str
        amount: float
        unit: str
    
    class OutputStructure(BaseModel):
        menu: str
        ingredient: list[Ingredient]
        steps: list[str]
        calorie_kcal: float
    

    Note: ดูวิธีใช้ BaseModel ได้ที่ JSON Schema

    หลังกำหนด system prompt, temperature, และ output type กับ structure แล้ว ให้เรารวมค่าทั้งหมดไว้ใน GenerateContentConfig() แบบนี้:

    # Set configuration
    gemini_config = GenerateContentConfig(
    
        # Set system prompt
        system_instruction=system_prompt,
    
        # Set temperature
        temperature=temp,
    
        # Set response type
        response_mime_type=output_type,
    
        # Set response structure
        response_schema=OutputStructure
    )
    

    Note: ดูค่าอื่น ๆ ที่เรากำหนดใน GenerateContentConfig() ได้ที่ Content generation parameters

    .

    📖 Generate Response

    หลังจากกำหนด arguments แล้ว เราจะเรียกใช้ function เพื่อ get response แบบนี้:

    # Generate a recipe
    recipe = get_response(
    
        # Set model
        model=gemini_model,
    
        # Set user prompt
        user_prompt=gemini_user_prompt,
    
        # Set configuration
        config=gemini_config
    )
    

    .

    สุดท้าย เราจะดู response ด้วย print():

    # Print response
    print(recipe)
    

    ผลลัพธ์:

    {
      "menu": "Thai Chicken Burger",
      "ingredient": [
        {
          "name": "Ground Chicken",
          "description": "Lean ground chicken",
          "amount": 150.0,
          "unit": "g"
        },
        {
          "name": "Whole-wheat Burger Bun",
          "description": "Standard size",
          "amount": 1.0,
          "unit": "unit"
        },
        {
          "name": "Lime Juice",
          "description": "Freshly squeezed",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Fish Sauce",
          "description": "Thai fish sauce",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Fresh Ginger",
          "description": "Grated",
          "amount": 1.0,
          "unit": "teaspoon"
        },
        {
          "name": "Garlic",
          "description": "Minced",
          "amount": 1.0,
          "unit": "clove"
        },
        {
          "name": "Cilantro",
          "description": "Fresh, chopped",
          "amount": 2.0,
          "unit": "tablespoons"
        },
        {
          "name": "Green Onion",
          "description": "Chopped",
          "amount": 1.0,
          "unit": "tablespoon"
        },
        {
          "name": "Red Chilli",
          "description": "Finely minced (optional)",
          "amount": 0.5,
          "unit": "teaspoon"
        },
        {
          "name": "Lettuce Leaf",
          "description": "Fresh, crisp",
          "amount": 1.0,
          "unit": "large"
        },
        {
          "name": "Cucumber",
          "description": "Sliced thinly",
          "amount": 3.0,
          "unit": "slices"
        },
        {
          "name": "Cooking Oil",
          "description": "Any neutral oil",
          "amount": 1.0,
          "unit": "teaspoon"
        }
      ],
      "steps": [
        "Combine ground chicken with fish sauce, lime juice, grated ginger, minced garlic, chopped cilantro, and green onion in a bowl. Mix thoroughly.",
        "Form the seasoned chicken mixture into a single, uniform burger patty. If using chilli, incorporate it now.",
        "Heat cooking oil in a non-stick pan over medium heat. Cook the chicken patty for 5-7 minutes per side, or until it is thoroughly cooked through.",
        "While the patty cooks, lightly toast the whole-wheat burger bun in a dry pan or toaster until golden brown.",
        "Assemble your burger: Place the cooked chicken patty on the bottom half of the toasted bun. Top with fresh lettuce and cucumber slices.",
        "Complete the burger with the top bun. Serve immediately and enjoy your healthy Thai-inspired meal."
      ],
      "calorie_kcal": 450.0
    }
    

    เท่านี้ก็จบ flow การทำงานกับ Gemini API ด้วย google-genai library แล้ว


    😺 Google Colab

    ดูตัวอย่าง code ทั้งหมดได้ที่ Google Colab


    📃 References