LoginSignup
633
679

JSONを返す無料APIを3分で作る方法

Last updated at Posted at 2018-03-04

JSONを返す無料APIを3分で作る方法

はじめに

この記事の読書対象者は以下のようなエンジニアです。

  • Ajaxで叩くAPIを用意してあげようとしている新人教育中の優しい先輩
  • なんかのサンプルアプリを作っているときのモックとして

既存データセット

ステータスコード等を返すAPI

こちらのサイトがほぼいい感じにAPIを良いしてくださってます。

ステータスコード200のレスポンスがほしいときは以下

curl -X GET "https://httpbin.org/status/200" -H "accept: text/plain"

 access-control-allow-credentials: true 
 access-control-allow-origin: * 
 content-length: 0 
 content-type: text/html; charset=utf-8 
 date: Sat, 16 Dec 2023 13:30:14 GMT 
 server: gunicorn/19.9.0 

画像がほしいときは

curl https://httpbin.org/image/jpeg

// jpeg画像が返ってくる

自分のIP調べたいときは

$ curl https://httpbin.org/ip

{
  "origin": "60.11.111.11"
}

お天気API

$ curl "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m"

{
  "current": {
    "time": "2022-01-01T15:00"
    "temperature_2m": 2.4,
    "wind_speed_10m": 11.9,
  },
  "hourly": {
    "time": ["2022-07-01T00:00","2022-07-01T01:00", ...]
    "wind_speed_10m": [3.16,3.02,3.3,3.14,3.2,2.95, ...],
    "temperature_2m": [13.7,13.3,12.8,12.3,11.8, ...],
    "relative_humidity_2m": [82,83,86,85,88,88,84,76, ...],
  }
}

jsonplaceholder

すでにいくつかのデータセットが用意されているので使いやすい

fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json))

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

API作成

  • 実際に通信する
    • Google Apps Script (GAS)で作成する
    • MyJson (既存のWebサービス)でJsonを登録する
  • ローカルサーバーを立てる
    • json-server(npmで導入する)

Google Apps Script(GAS)を使う

以下のコードをGASに貼り付けて、「公開」「ウェブアプリケーションとして導入」を押して発行されたURLを叩くと文字列のJSONが返ってくる。

function doGet(e) {
  return ContentService.createTextOutput(JSON.stringify({'name': 'Qiita'}))
    .setMimeType(ContentService.MimeType.JSON);
}

スクリーンショット

参考: https://developers.google.com/apps-script/guides/content#serving_json_from_scripts

GetメソッドにtokenをつけてたらJsonを返すとかそういう処理もできるのでオススメ!

localにjson-serverを立てて使う

Node.js等を使える人はjson-serverがおすすめみたいです!

参考:JSON Serverを使って手っ取り早くWebAPIのモックアップを作る

npm install -g json-server

npmインストールとか必要だけどAPIモックにするのにはすごく便利なのでオススメ!

API GatewayのMockを使う

awsサービス使っている方は楽

Qiita

QiitaのAPIを使う。認証してないと1時間に60回という制限付きだが普通に使えると思う。
この記事のlikeをしてくれたユーザー一覧を取得する場合。

.httpファイルでREST clientアプリから取得してみるなら以下のようになる

$ touch test.http
$ vim test.http

# GET /api/v2/items/:item_id/likes
# https://qiita.com/api/v2/docs#get-apiv2itemsitem_idlikes
# https://qiita.com/ykhirao/items/a41322085ab55837b88e

GET https://qiita.com/api/v2/items/a41322085ab55837b88e/likes
HTTP/1.1 200 OK
Date: Mon, 11 Dec 2023 05:48:50 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Server: nginx
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Download-Options: noopen
X-Permitted-Cross-Domain-Policies: none
Referrer-Policy: strict-origin-when-cross-origin
Link: <https://qiita.com/api/v2/items/a41322085ab55837b88e/likes?page=1>; rel="first", <https://qiita.com/api/v2/items/a41322085ab55837b88e/likes?page=2>; rel="next", <https://qiita.com/api/v2/items/a41322085ab55837b88e/likes?page=32>; rel="last"
Total-Count: 634
ETag: W/"df875ddadb9e3b1357f1c26cae6e8c28"
Cache-Control: max-age=0, private, must-revalidate
Rate-Limit: 60
Rate-Remaining: 59
Rate-Reset: 1702277330
Vary: Origin
X-Request-Id: fcce504f-356b-4d0a-bbb7-db2be19d2c84
X-Runtime: 0.732132
Strict-Transport-Security: max-age=2592000

[
  {
    "created_at": "2023-02-08T03:54:58+09:00",
    "user": {
      "description": "勉強中",
      "facebook_id": "",
      "followees_count": 1,
      "followers_count": 1,
      "github_login_name": null,
      "id": "user_name",
      "items_count": 1,
      "linkedin_id": "",
      "location": "",
      "name": "",
      "organization": "",
      "permanent_id": 1,
      "profile_image_url": "image_url",
      "team_only": false,
      "twitter_screen_name": null,
      "website_url": "your_site"
    }
  }
]

その他

Gistを使ってもいけた。

var url = 'https://api.github.com/gists/3137d994d72040d00a84f422349757d4';

fetch( url )
.then( function( data ) {
  return data.json();
})
.then( function( json ) {
  console.log( json.files['sample.json'].content );
})
# json
curl https://api.github.com/gists/3137d994d72040d00a84f422349757d4

お手軽ではないです。

終わりに

AjaxとかAPIとかよくわかってなかった時期がありました。それくらいのレベルの人に教えるときに先輩エンジニアが「API作っといたのでこれ自由に叩いていいよ」って感じの世界素敵ですね!!

それでは素敵なAPIライフを!!

残念ながらなくなったサービス

Json okibaというWebサービスを使う

633
679
5

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
633
679