0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(Python)標準モジュールだけで公開APIからGET

Last updated at Posted at 2023-12-09

はじめに

Requestsライブラリ使わないで公開API叩きたい
subprocessでcurlすればいいんじゃないか

コード

とりあえず画面

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>テスト</title>
</head>
<body>

<p>ホスト名/パス/クエリでGETリクエスト送ります</p>

<p>
<label><input type="text" id="hpq" placeholder="宛先"></label>
<input type="button" value="GET" onclick="ButtonClick(this)">
</p>

<p id="msg"></p>
<script type="text/javascript">

function ButtonClick(button){
	let xhl = new XMLHttpRequest();
	let formData = new FormData();
	formData.append("hpq", encodeURIComponent(document.getElementById('hpq').value));
	xhl.open('POST', 'request.py', false);
	xhl.setRequestHeader( 'Content-Type', 'Multipart/form-data' );
	xhl.send(formData);
	document.getElementById('msg').innerText = xhl.response;
}
</script>

</body>
</html>

フォームに入れた宛先をrequest.pyにPOST→request.pyの中でGET投げるって感じで...
スクリーンショット 2023-12-09 231420.png

Pythonはこれ
pacモジュール(自作パッケージだからpacとかいう命名の安直さ!)の中身はこないだの記事の使い回し
標準入力の解析の命名がmake_propertyってどうなんだろうね

request.py
#!/usr/local/bin/python3.9

import pac
import subprocess

class Request:
	def __init__(t):

		#プロパティにGETパラメタセット
		pac.make_property(t)
		#コンストラクタ内でgetメソッド叩く
		t.get()

	def get(t):

		try:
			res = subprocess.run('curl -X GET ' + 'https://' + t.hpq, shell=True, encoding='utf-8', check=True, stdout=subprocess.PIPE)
			Request.out(res.stdout)
		except subprocess.CalledProcessError as err:
			Request.out('あ~コケてますね\n' + str(err))

	def out(t):

		print('Status: 200 OK')
		print('Content-Type: application/json\n')
		#json.loadsの方がいいかも、叩くAPIの仕様による感はある
		print(t)
		exit()

#インスタンス化
Request()

試しに
zipcloud.ibsnet.co.jp/api/search?zipcode=1000000
で郵便番号から住所取る
スクリーンショット 2023-12-09 232200.png

POSTの時とかトークン必要な時もこれの拡張でいけるね
作るのがめんどくさかっただけ

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?