0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【初心者向け、上級開発者お断り!】インフラエンジニアが学ぶはじめてのAPI in 東京 メモ

Posted at

【初心者向け、上級開発者お断り!】インフラエンジニアが学ぶはじめてのAPI in 東京 メモ

DHCPの割当IPアドレスの不足によりアクセスできない方がいた
(→自社で勉強会を開催するときには考慮すること)

宣伝:LXC(GMO独自コンテナ)

はやい、安い、簡単(多分)

仮想基盤の構築は難しい
特にネットワーク周り
そこをカプセル化により簡略化し使いやすくしている

座学

なぜAPIを使うのか

iPhone、Android、PCそれぞれ専用の機能を作るのが面倒
→APIを作っておき、それぞれの端末からAPIを呼び出す

APIの呼び出しが煩雑になる問題が…
→「REST」というルールを設けて煩雑にならないようにする

命令:POST PUT GET DELETE
構文:URL URI

/user:ユーザー操作をするということがわかる

get:ユーザーのデータを取得する
post:ユーザーデータを登録する
put:更新
delete:削除

RESTで開発していると明示するだけで、外部のユーザーが利用しやすく、使い方が共有しやすい

APIハンズオン

以下のURLにアクセスする。
ハンズオンサイト
http://handson.gmo-digirock.info/

(0とOが区別できるフォントで印刷してほしい…)

Livedoor天気予報のAPIを叩く

ブラウザでアクセス

http://weather.livedoor.com/forecast/webservice/json/v1?city=270000
見にくい…!!

curlでアクセスし、jqコマンドで整形する

curl http://weather.livedoor.com/forecast/webservice/json/v1?city=270000 | jq .

ちょっと見やすくなった

ブラウザ上のphpでアクセスする

市区コードを変えると表示内容が変わる

weather.php
<?php
	$data = [];
	$city = 270000;
	if(!empty($_GET["city"])){
    <!-- 変数 -->
		$url = "http://weather.livedoor.com/forecast/webservice/json/v1?city={$_GET["city"]}";
		$data = json_decode(file_get_contents($url));
		$city = $_GET["city"];
	}
	?>


	<html>
	<head>
		<title>ハンズオン - 天気API</title>

		<style>
		table { margin-bottom:3px;}
		</style>
		<meta charset="utf-8"/>
	</head>
	<body>

	<a href="http://weather.livedoor.com/forecast/rss/primary_area.xml" target="_blank">市区コード一覧</a>

	<form action="" >
		<input type="text" name="city" value="<?php echo($city); ?>">市区コード
		<input type="submit" name="送信">
	</form>
  <!-- 出力部分 -->
	<?php
		echo <<< HTML_BODY
		<p>{$data->location->prefecture}{$data->location->city}市の今日の天気</p>
HTML_BODY;
		foreach($data->forecasts as $k=>$v){
			echo <<< HTML_BODY
			<table border="1" >
			<tr><td colspan="2">{$v->dateLabel}の天気</tr>
			<tr>
				<td>日時</td>
				<td>{$v->date}</td>
			</tr>
			<tr>
				<td>天気</td>
				<td>{$v->telop}</td>
			</tr>
			<tr>
				<td>最低気温</td>
				<td>{$v->temperature->min->celsius}</td>
			</tr>
			<tr>
				<td>最高気温</td>
				<td>{$v->temperature->max->celsius}</td>
			</tr>

			</table>

HTML_BODY;
		}
	?>
	</body>
	</html>

簡単なプログラミングの知識があれば、
APIを組み合わせて簡単にサービスを作ることができる!

XREA API

XREA APIキー発行

GMOのサービスXREAはAPI経由の操作に対応しており、
JSON形式でやり取りする

XREA DB作成

※XXXX部分は適宜変更すること

curl -X POST \
-d "account=XXXXXXXXXXX" \
-d "server_name=XXXXX.xrea.com" \
-d "api_secret_key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-d "db_type=mysql" \
https://api.xrea.com/v1/db/list | jq .

XREA DB確認

curl -X POST \
-d "account=XXXXXXXXXXX" \
-d "server_name=XXXXX.xrea.com" \
-d "api_secret_key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-d "param[0][db_name]=XXXXXXXXXXX_testdb" \
-d "param[0][db_pass]=XXXXXXXX" \
-d "param[0][code]=unicode" \
-d "db_type=mysql" \
https://api.xrea.com/v1/db/add | jq .

Twitter API

TwitterAPIの取得には15〜20日かかる(長い)
ハンズオンでは事前に取得していただいたAPIを利用する

※XXXX部分は適宜変更すること

画面作成

twitter.php
<html>
<head>
    <title>Tweets Search</title>
</head>
<body>
<h1>Tweets Search</h1>
<form action="./twitter.php" method="GET">
keyword : <input type="text" name="q" value=""/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

http://www.XXXXXXXXXXX.shop/twitter.php
画面ができる

URLから値を取得しテキストボックスへ入力

twitter.php
<!--URLから値を取得する-->
<?php
// GET Request Paramater
$q = $_GET['q']?$_GET['q']:"GMO";
?>
<html>
<head>
    <title>Tweets Search</title>
</head>
<body>
<h1>Tweets Search</h1>

<!--テキストボックスに入れる-->
<?php
echo <<<EOF
<form action="./twitter.php" method="GET">
    keyword : <input type="text" name="q" value="{$q}"/><br/>
    <input type="submit" value="submit"/>
</form>
EOF;
?>
</body>
</html>

http://www.XXXXXXXXXXX.shop/twitter.php
キーワードがテキストボックス内に残るようになる

検索結果表示

twitter.php
<?php
// Twitter Library
require 'TwistOAuth.phar';

// API Key
$consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

// Twitter Library
$connection = new TwistOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);

// GET Request Paramater
$q = $_GET['q']?$_GET['q']:"GMO";

// Search Tweets
$tweets_params = ['q' => $q ,'count' => '10'];
$tweets = $connection->get('search/tweets', $tweets_params)->statuses;

var_dump($tweets);
?>
<html>
<head>
    <title>Tweets Search</title>
</head>
<body>
<h1>Tweets Search</h1>

<?php
echo <<<EOF
<form action="./twitter.php" method="GET">
    keyword : <input type="text" name="q" value="{$q}"/><br/>
    <input type="submit" value="submit"/>
</form>
EOF;
?>
</body>
</html>

http://www.XXXXXXXXXXX.shop/twitter.php
Twitterの検索結果を取得できるようになる

Oauth認証でアクセストークン・アクセストークンシークレットを入手できる
(今回は準備されていたので省略)

 表示整形

twitter.php
<?php
// Twitter Library
require 'TwistOAuth.phar';

// API Key
$consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';


// Twitter Library
$connection = new TwistOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);

// GET Request Paramater
$q = $_GET['q']?$_GET['q']:"GMO";

// Search Tweets
$tweets_params = ['q' => $q ,'count' => '10'];
$tweets = $connection->get('search/tweets', $tweets_params)->statuses;

// var_dump($tweets);
?>
<html>
<head>
    <title>Tweets Search</title>
</head>
<body>
<h1>Tweets Search</h1>

<?php
echo <<<EOF
<form action="./twitter.php" method="GET">
    keyword : <input type="text" name="q" value="{$q}"/><br/>
    <input type="submit" value="submit"/>
</form>
EOF;
// Show List
foreach ($tweets as $value) {
    $text = htmlspecialchars($value->text, ENT_QUOTES, 'UTF-8', false);
    echo $text;
    echo "<br/>";
}
?>
</body>
</html>

Twitterアイコン表示

twitter.php
<?php
// Twitter Library
require 'TwistOAuth.phar';

// API Key
$consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';


// Twitter Library
$connection = new TwistOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);

// GET Request Paramater
$q = $_GET['q']?$_GET['q']:"GMO";

// Search Tweets
$tweets_params = ['q' => $q ,'count' => '10'];
$tweets = $connection->get('search/tweets', $tweets_params)->statuses;

// var_dump($tweets);
?>
<html>
<head>
    <title>Tweets Search</title>
</head>
<body>
<h1>Tweets Search</h1>

<?php
echo <<<EOF
<form action="./twitter.php" method="GET">
    keyword : <input type="text" name="q" value="{$q}"/><br/>
    <input  type="submit" value="submit"/>
</form>
EOF;
// Show List
foreach ($tweets as $value) {
    $text = htmlspecialchars($value->text, ENT_QUOTES, 'UTF-8', false);
    // mathing keyword
    $keywords = preg_split('/,|\sOR\s/', $tweets_params['q']);
    foreach ($keywords as $key) {
        $text = str_ireplace($key, '<b>'.$key.'</b>', $text);
    }
    disp_tweet($value, $text);
}

// Show Tweets
function disp_tweet($value, $text){
    $icon_url = $value->user->profile_image_url;
    $screen_name = $value->user->screen_name;
    $updated = date('Y/m/d H:i', strtotime($value->created_at));
    $tweet_id = $value->id_str;
    $url = 'https://twitter.com/' . $screen_name . '/status/' . $tweet_id;

    echo <<<TWEET
<div class="thumb"><img alt="" src="{$icon_url}"><a target="_blank" href="{$url}">@{$screen_name}</a></div>
<div class="tweet">{$text}</div>
<div class="meta">({$updated})</div>
<br/>
TWEET;
}
?>
</body>
</html>
0
3
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
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?