1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RustでHTTPリクエストを送りレスポンスを受け取るサンプル(サーバー実装付き)

1
Posted at

概要

最近Rustを触れ始め、ちょっとしたツールを作るのにいいな~と感じました。

開発中は何かとAPIにリクエストを送ることがあるので、

  • Rustのインストール
  • cargoプロジェクト作成
  • HTTPリクエストしてレスポンスを受け取る

までの簡単なサンプルを備忘録として残します。

やること

  1. ローカルに簡易なAPIを作る
  2. Rustをインストール
  3. RustでAPIへリクエストを送り、レスポンスをテキストのまま出力する

1. ローカルに簡易なAPIを作る

TypeScript + Expressで実装してます。

> mkdir server && cd server
> npm init
# 諸々の質問が来るので答える
> npm install express 
> npm install -D typescript @types/node @types/express
> npx tsc --init

※任意 tsconfig.jsonを少し変え、srcとdistディレクトリの設定を行います。

{
  "compilerOptions": {
    // File Layout
    "rootDir": "./src",
    "outDir": "./dist",

    "module": "esnext",
    "target": "esnext",
    "types": ["node"],
    "sourceMap": true,
    "declaration": true,
    "declarationMap": true,

    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,

    // Recommended Options
    "strict": true,
    "jsx": "react-jsx",
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "noUncheckedSideEffectImports": true,
    "moduleDetection": "force",
    "skipLibCheck": true,
  }
}

サーバー側を実装します。

> mkdir src
> toush src/index.ts

index.ts

import express from "express";

const app = express();
const HOST = "http://localhost";
const PORT = 3000;

type Product = {
  name: string;
  price: number;
  stock: number;
};

app.get("/", (req: express.Request, res: express.Response) => {
  res.send("hello");
});

app.get("/products", (req: express.Request, res: express.Response) => {
  const products: Array<Product> = [
    { name: "にんじん", price: 100, stock: 10 },
    { name: "玉ねぎ", price: 200, stock: 20 },
    { name: "じゃがいも", price: 300, stock: 30 },
  ];
  res.send(JSON.stringify(products));
});

console.log(`Start Server: ${HOST}:${PORT}`);
app.listen(3000);

サーバーを起動します

> npx tsc && node dist/index.js
Start Server: http://localhost:3000

起動できました

2. Rustのインストール

公式ページに従いました。
自分は普段WSLを使っているので

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

これだけでインストールできました。ありがたや~
ここでcargoも一緒に入ります。

3. RustでAPIへリクエストを送り、レスポンスをテキストのまま出力する

cargoプロジェクトの作成

> cargo new client && cd client

これでプロジェクトが作成され、Hello Worldする準備が整うはずです。確認します。

$ cargo run
   Compiling temp v0.1.0 (/home/user/client)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.44s
     Running `target/debug/client`
Hello, world!

良さそうですね

必要なライブラリのインストールです。

HTTPリクエストのライブラリを探したところreqwestというものが見つかり、シンプルそうでしたのでこちらを入れます。
また、reqwestのサンプルコードには非同期用のライブラリtokioが使われておりましたので、こちらも合わせてインストールします。

> cargo add reqwest tokio

HTTPリクエストの実装

cargoプロジェクトのsrc/main.rsを下記のように実装します

use reqwest;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "http://localhost:3000/";
    let response = reqwest::get(url).await?;
    println!("{}", response.text().await?);
    Ok(())
}

実行してましょう

$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
     Running `target/debug/client`
hello

サーバー側で実装した/へのリクエストが送られ、helloが返されました。リクエストに成功していそうです。

今後は/productsへリクエストしてみます

let url = "http://localhost:3000/products";
$ cargo run
   Compiling client v0.1.0 (/home/user/client)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.72s
     Running `target/debug/client`
[{"name":"にんじん","price":100,"stock":10},{"name":"玉ねぎ","price":200,"stock":20},{"name":"じゃがいも","price":300,"stock":30}]

無事にJSON化された文字列を受け取れていそうですね

終わりに

RustでHTTPリクエストを送る簡単なサンプルを実装してみました。

余談ですが、今日はカレーの気分でした。

1
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?