LoginSignup
3
2

More than 3 years have passed since last update.

noteのAPIを使用して、記事の詳細を取得する方法

Posted at

開発環境

vue.js (vue-cli 2.0)
firebase
bootstrap

noteのAPIの利用方法

こちらの方法を用いて、noteの評価掲示板サービスを作りました。
https://www.note-2channel.work/

このサービスを作る際に、noteのAPIを使用したのでその方法を記載します。

検索すると、こんな記事を見つけました
https://note.com/hagure_melon/n/n964ff6f7ad0e

その中に

↑このようなnoteのAPIを取得するコードがありました。
(nafc8a5836d3fは記事のkey)

というわけで実際に取得できるか試してみました。

test.js

var request = require("sync-request");

var url = "https://note.com/api/v1/notes/nafc8a5836d3f";

var res = request("GET",url);

var res_json = res.getBody("utf-8");

// console.log(res.getBody("utf-8"));

const obj = JSON.parse(res_json);//オブジェクトをJSONとして文字列として出力
//parse=JSON形式の文字列を文字列として置き換える

ターミナルで node test.js
と実行したところ、問題なくnoteの記事の詳細がjson形式でparseされました!

nodeを実行するにはfirebaseのfunctionsを利用して、関数をデプロイすれば良いということだったので、そのためにコードを書きます。

プロジェクトのfunctions内にindex.jsを用意して、そこに記述します。

index.js


const functions = require('firebase-functions');

exports.helloOnCall = functions.https.onCall((data, context) => {//ここに書いたものがfirebase経由でしかアクセスできない

  var request = require("sync-request");
  var url = "https://note.com/api/v1/notes/" + data;
  var res = request("GET",url);
  var res_json = res.getBody("utf-8");

  const obj = JSON.parse(res_json);//オブジェクトをJSONとして文字列として出力
  //parse=JSON形式の文字列を文字列として置き換える

  const return_res = {
    name: obj.data.name
  };


  return return_res;
});

//firebase経由でしか接続されないようにする。

まずはこれでapiを呼び出す関数を定義します。
次にfirebase functionsにhelloOnCall関数を登録します。

note.js

const firebase = require("firebase");

var firebaseConfig = {
  apiKey: "XXX",
  authDomain: "XXXX",
  projectId: "XXX",
  storageBucket: "XXXX",
  messagingSenderId: "3XXX",
  appId: "XXXXXX",
  measurementId: "XXXXXXX",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

const functions = firebase.functions();

functions.useFunctionsEmulator("http://localhost:5001"); //ローカルでfirebaseにアクセスするもの

const main = async () => {
  const helloOnCall = functions.httpsCallable("helloOnCall");
  const res = await helloOnCall("n40187a5c671b");
  console.log(res);
};

main();

//firebaseでAPIアクセス


そしてターミナルを別枠で開き、
firebase emulators:start --only functions
を起動しておく。

node note.jsを実行

これでしっかりコンソールにデータが表示されたら、helloOnCall関数は機能しています。
あとは適宜呼び出すだけ!

call: function() {
      var search_note = firebase.functions().httpsCallable("helloOnCall");
      search_note("noteのkey").then((res) => {
        console.log(res.data);
}

この方法で私はAPIを利用しました!

注意点

functionsを使用する際に、プランを従量課金のBlazeに変更しなくてはいけませんでした。

3
2
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
3
2