以下課題に取り組んでいます。
以下の3つのWeb APIがあります(実際にアクセスできます)。これらを利用して、あるユーザーIDをあたえたときのユーザー名および登録金融機関一覧と、登録金融機関の残高(balance)を出力するプログラムを作成してください。 なお、プログラムはオブジェクト指向プログラミングに基づく設計・実装をしてください。
json:hoge.json
1 2- Web API 3 - https://salty-forest-61016.herokuapp.com/users/1 4 - レスポンス例 5 { 6 attributes: { 7 id: 1, 8 name: "Alice", 9 account_ids: [ 10 1, 11 3, 12 5 13 ] 14 } 15 } 16 - https://salty-forest-61016.herokuapp.com/users/1/accounts 17 - レスポンス例 18 [ 19 { 20 attributes: { 21 id: 1, 22 user_id: 1, 23 name: "A銀行", 24 balance: 20000 25 } 26 }, 27 { 28 attributes: { 29 id: 3, 30 user_id: 1, 31 name: "C信用金庫", 32 balance: 120000 33 } 34 }, 35 { 36 attributes: { 37 id: 5, 38 user_id: 1, 39 name: "E銀行", 40 balance: 5000 41 } 42 } 43 ] 44 45 - https://salty-forest-61016.herokuapp.com/accounts/2 46 - レスポンス例 47 { 48 attributes: { 49 id: 2, 50 user_id: 2, 51 name: "Bカード", 52 balance: 200 53 } 54 } 55
Qiitaで独学しました。
課題を解く前に、独学で自分なりにQiitaにまとめました。
Web API 学習(非公開記事)
個人的回答(最低限回答になってます。)
※ 最低限の回答 ... $ ruby hoge.rb
で動く。
require 'net/http' require 'uri' require 'json' class User attr_reader :userid def initialize(userid) @userid = userid end def name url = URI.parse("https://salty-forest-61016.herokuapp.com/users/#{@userid}") json = Net::HTTP.get(url) user = JSON.parse(json) puts user['attributes']['name'] end def accounts url = URI.parse("https://salty-forest-61016.herokuapp.com/users/#{@userid}/accounts") json = Net::HTTP.get(url) accounts = JSON.parse(json) accounts.each do |account| puts "銀行名:#{account["attributes"]["name"]}(残高: #{account['attributes']['balance']}円)" end end end user = User.new(1) user.name # Alice user.accounts # 銀行名:A銀行(残高: 20000円) # 銀行名:C信用金庫(残高: 120000円) # 銀行名:E銀行(残高: 5000円)
$ ruby hoge.rb
で動かしています。
もっと良いコードにしてみたい
考えてること | 補足 | |
---|---|---|
0 | 課題の意図通りかな。 | ちょっと心配。 |
1 | リファクタリングをしてみたい! | 独学なのでteratailの先輩にアドバイスお願いしたいです! |
2 | 3つ目のURL使わなくていいのか。 | 色々な回答があると思うので幅広く知りたいです。 |
3 | 処理速度を早めた実装 | (何を持って速いのかも分かっていません。。。) |
4 | エラー対応を早めた実装 | User.new(100) だとユーザがいないためエラーです。これをどう実装するか考えています。 |
ご助言、アドバイス、頂ける方、お願いできないでしょうか。
お手数ですが、よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。