Thực Hiện Yêu Cầu API Bằng Nhiều Ngôn Ngữ Lập Trình

Trong kỷ nguyên số hóa hiện nay, Giao diện Lập trình Ứng dụng (API) đóng vai trò trung tâm, cho phép các dịch vụ và ứng dụng độc lập trao đổi dữ liệu và chia sẻ chức năng. Dù là để truy xuất dự báo thời tiết, dữ liệu mạng xã hội, hay xử lý thanh toán, API đều là thành phần cốt lõi. Mỗi ngôn ngữ lập trình cung cấp các thư viện và phương pháp riêng biệt để tương tác với các API. Dưới đây là cách thực hiện các yêu cầu API bằng một số ngôn ngữ phổ biến như Python, JavaScript, Java, C# và Ruby.

Python

Python là lựa chọn hàng đầu cho việc xử lý dữ liệu và gọi API nhờ cú pháp rõ ràng và hệ sinh thái thư viện phong phú. Thư viện requests là phương pháp được ưa chuộng nhất.

Ví dụ Python:

import requests

def fetch_data_from_api(endpoint_url):
    """Thực hiện yêu cầu GET tới API và in ra dữ liệu phản hồi."""
    try:
        api_response = requests.get(endpoint_url)
        api_response.raise_for_status()  # Ném lỗi cho các mã trạng thái HTTP không thành công (4xx hoặc 5xx)

        print(f"Yêu cầu thành công với mã trạng thái: {api_response.status_code}")
        content_data = api_response.json()  # Giả sử API trả về JSON
        print("Dữ liệu nhận được:")
        print(content_data)
    except requests.exceptions.HTTPError as http_err:
        print(f"Lỗi HTTP xảy ra: {http_err}")
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Lỗi kết nối xảy ra: {conn_err}")
    except requests.exceptions.Timeout as timeout_err:
        print(f"Thời gian chờ yêu cầu đã hết: {timeout_err}")
    except requests.exceptions.RequestException as e:
        print(f"Có lỗi xảy ra trong quá trình yêu cầu: {e}")

# Gọi hàm với URL API mẫu
fetch_data_from_api("https://api.example.com/data")

JavaScript

Trong môi trường trình duyệt, JavaScript sử dụng fetch hoặc XMLHttpRequest để gọi API. Đối với môi trường Node.js, các thư viện như axios hoặc node-fetch được khuyến nghị.

Ví dụ JavaScript (Trình duyệt với Fetch API):

const apiEndpoint = "https://api.example.com/data";

fetch(apiEndpoint)
    .then(response => {
        if (!response.ok) {
            throw new Error(`Lỗi HTTP! Mã trạng thái: ${response.status}`);
        }
        return response.json(); // Phân tích phản hồi JSON
    })
    .then(data => {
        console.log("Dữ liệu nhận được:", data);
    })
    .catch(error => {
        console.error("Đã xảy ra lỗi khi gọi API:", error);
    });

Ví dụ JavaScript (Node.js với Axios):

const axios = require('axios');

async function getApiResource(url) {
    try {
        const httpResponse = await axios.get(url);
        console.log("Dữ liệu từ API:", httpResponse.data);
    } catch (err) {
        console.error("Lỗi khi tải tài nguyên:", err.message);
        if (err.response) {
            console.error("Dữ liệu lỗi:", err.response.data);
            console.error("Mã trạng thái:", err.response.status);
        } else if (err.request) {
            console.error("Không nhận được phản hồi:", err.request);
        }
    }
}

getApiResource('https://api.example.com/data');

Java

Trong Java, việc gửi yêu cầu HTTP thường được thực hiện thông qua HttpURLConnection có sẵn trong JDK, hoặc các thư viện bên thứ ba như Apache HttpClient hay OkHttp.

Ví dụ Java (Sử dụng HttpURLConnection):

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiRequester {
    public static void main(String[] args) {
        String targetUrl = "https://api.example.com/data";
        try {
            URL urlObject = new URL(targetUrl);
            HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();

            // Thiết lập phương thức yêu cầu và header
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");

            int httpResponseCode = connection.getResponseCode();
            System.out.println("Mã phản hồi HTTP: " + httpResponseCode);

            if (httpResponseCode == HttpURLConnection.HTTP_OK) { // 200 OK
                BufferedReader inputReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder responsePayload = new StringBuilder();

                while ((inputLine = inputReader.readLine()) != null) {
                    responsePayload.append(inputLine);
                }
                inputReader.close();

                // In ra phản hồi (giả sử là JSON hoặc văn bản)
                System.out.println("Nội dung phản hồi:");
                System.out.println(responsePayload.toString());
            } else {
                System.out.println("Yêu cầu GET không thành công. Mã lỗi: " + httpResponseCode);
                // Đọc luồng lỗi nếu có
                try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    String errorLine;
                    StringBuilder errorResponse = new StringBuilder();
                    while ((errorLine = errorReader.readLine()) != null) {
                        errorResponse.append(errorLine);
                    }
                    if (errorResponse.length() > 0) {
                        System.out.println("Thông báo lỗi từ máy chủ: " + errorResponse.toString());
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("Đã xảy ra lỗi: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

C#

Trong C#, lớp HttpClient cung cấp cách thức tiện lợi để gửi các yêu cầu HTTP và xử lý phản hồi một cách bất đồng bộ.

Ví dụ C# (Sử dụng HttpClient):

using System;
using System.Net.Http;
using System.Threading.Tasks;

class WebApiClient
{
    static async Task Main(string[] args)
    {
        string apiEndpoint = "https://api.example.com/data";

        using (HttpClient httpClient = new HttpClient())
        {
            try
            {
                HttpResponseMessage httpResponse = await httpClient.GetAsync(apiEndpoint);
                httpResponse.EnsureSuccessStatusCode(); // Ném HttpRequestException nếu mã trạng thái không thành công

                string responseData = await httpResponse.Content.ReadAsStringAsync();
                Console.WriteLine("Dữ liệu nhận được từ API:");
                Console.WriteLine(responseData); // In ra JSON hoặc dữ liệu khác
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"Lỗi yêu cầu HTTP: {ex.Message}");
                if (ex.StatusCode.HasValue)
                {
                    Console.WriteLine($"Mã trạng thái lỗi: {(int)ex.StatusCode.Value}");
                }
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"Chi tiết lỗi: {ex.InnerException.Message}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Đã xảy ra lỗi không mong muốn: {ex.Message}");
            }
        }
    }
}

Ruby

Trong Ruby, thư viện chuẩn net/http thường được dùng cho các yêu cầu HTTP cơ bản, và httparty là một thư viện bên thứ ba phổ biến hơn với cú pháp dễ sử dụng.

Ví dụ Ruby (Sử dụng net/http):

require 'net/http'
require 'json'
require 'uri' # Cần thiết để phân tích URL

def fetch_external_data(data_uri)
    target_uri = URI.parse(data_uri)
    
    # Tạo yêu cầu HTTP GET
    http_get_request = Net::HTTP::Get.new(target_uri.request_uri)

    # Gửi yêu cầu và nhận phản hồi, đảm bảo kết nối SSL cho HTTPS
    http_response = Net::HTTP.start(target_uri.hostname, target_uri.port,
                                    use_ssl: target_uri.scheme == 'https') do |http|
        http.request(http_get_request)
    end

    if http_response.is_a?(Net::HTTPSuccess)
        parsed_body = JSON.parse(http_response.body)
        puts "Dữ liệu API nhận được:"
        puts parsed_body
    else
        puts "Yêu cầu không thành công. Mã trạng thái: #{http_response.code}"
        puts "Thông báo lỗi: #{http_response.message}"
        puts "Nội dung lỗi: #{http_response.body}" if http_response.body && !http_response.body.empty?
    end
rescue StandardError => e
    puts "Đã xảy ra lỗi trong quá trình yêu cầu: #{e.message}"
end

# Gọi hàm với URL API mẫu
fetch_external_data("https://api.example.com/data")

Thẻ: python JavaScript Java C# ruby

Đăng vào ngày 3 tháng 11 lúc 09:47