1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#入門 第11章】APIとの通信入門|Webとつながるアプリを作ろう!

Posted at

【C#入門 第11章】APIとの通信入門|Webとつながるアプリを作ろう!

お待たせ、 CSharpTimes の一之瀬シィよ💠
今回からC#が Webの世界とつながる フェーズに突入よ。
REST APIにアクセスして、リアルな外部データを取得・利用できるようになりましょ!


🌐 APIってなに?

API(Application Programming Interface) とは、
外部サービスやアプリと データをやり取りする窓口 のことよ。

  • 天気情報を取得したり
  • チャットボットと通信したり
  • データベースとつないだり

全部、APIで実現できるの!


🛠 API通信には HttpClient を使う!

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

class Program
{
    static async Task Main(string[] args)
    {
        HttpClient client = new HttpClient();
        string url = "https://api.agify.io/?name=shii";

        HttpResponseMessage response = await client.GetAsync(url);
        string result = await response.Content.ReadAsStringAsync();

        Console.WriteLine("APIの返答:" + result);
    }
}

📘 上のコード解説

  • HttpClient:APIへリクエストを送るためのクラス
  • GetAsync():指定したURLにGETリクエストを送信
  • ReadAsStringAsync():レスポンスを文字列として読み取り
  • await:非同期処理の完了を待つ

📦 JSONを扱うなら System.Text.Json

using System.Text.Json;

var data = JsonSerializer.Deserialize<Dictionary<string, object>>(result);
Console.WriteLine("予測年齢:" + data["age"]);

✅ 非同期関数の注意点

  • Main()async Taskに変更しないとawaitは使えないわ
  • コンソールアプリで非同期はちょっとクセがあるけど、慣れなさい💢

📌 まとめ

  • HttpClientでWeb APIと通信できる
  • 非同期処理(await)でスマートに動かせる
  • JSONレスポンスを解析するにはJsonSerializerが便利

次回は、 「第12章:ログ出力とエラーハンドリング」 よ。
“本番環境の落とし穴”に耐えられる強いアプリを作る準備、しておきなさいよ💢

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?