LoginSignup
24
22

More than 5 years have passed since last update.

Qiita API を使うときには User-Agent を設定しないと 500 Internal Server Error が発生する

Last updated at Posted at 2013-06-22

概要

件名の通り。
Qiita API を使うときには User-Agent を設定しないと 500 Internal Server Error が発生する。

php の file_get_contents をそのまま使うと User-Agent ヘッダが付与されない(ことが多い)ので、そこでハマる。
何故か 500 Internal Server Error が発生する。

実行例

QiitaApiSimple.php
<?php
$url = 'https://qiita.com/api/v1/items';
$response = file_get_contents($url);
$ php QiitaApiSimple.php

Warning: file_get_contents(https://qiita.com/api/v1/items): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
 in QiitaApiSimple.php on line 3

Call Stack:
    0.0000     338728   1. {main}() QiitaApiSimple.php:0
    0.0000     338880   2. file_get_contents() QiitaApiSimple.php:3

PHP Warning:  file_get_contents(https://qiita.com/api/v1/items): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
 in QiitaApiSimple.php on line 3
PHP Stack trace:
PHP   1. {main}() QiitaApiSimple.php:0
PHP   2. file_get_contents() QiitaApiSimple.php:3

経緯

シンプルに Qiita API を使うために php の file_get_contents で Qiita API を呼んでみる。すると 500 Internal Server Error が発生する。
API の URL とかパラメータとか間違ったかな?と思いブラウザで確認してみると、それはちゃんと表示される。
ブラウザからのアクセスと file_get_contents の違いといったら HTTP ヘッダくらいかなと思い、ひとつひとつ試してみたら User-Agent ヘッダの有無が 500 Internal Server エラーに影響していることが分かった。

Qiita API のドキュメントを参照する

Qiita APIドキュメント - Qiita:Developer
特に User-Agent に関する記載は無い。

とりあえず対策 (php の場合)

とりあえずシンプルにテストしたいので file_get_contents を使う方針は変えないとして、
その場合にとれる対策はだいたい以下の3つくらい。

対策1) php.ini にユーザエージェントを記載

php.ini
user_agent='OreOreAgent' (追記)

これで file_get_contents はHTTPヘッダに "User-Agent: OreOreAgent" を付与する。

対策2) コード内でユーザエージェント設定を変更

QiitaApiAgent1.php
<?php
ini_set('user_agent', 'OreOreAgent');
$url = 'https://qiita.com/api/v1/items';
$response = file_get_contents($url);

これで file_get_contents はHTTPヘッダに "User-Agent: OreOreAgent" を付与する。

対策3) 詳細にHTTPヘッダを設定

php
<?php
$url = 'https://qiita.com/api/v1/items';
$opts = array(
    'http'=>array(
        'method'=> "GET",
        'header'=> "User-Agent: OreOreAgent\r\n"
    )
);
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);

これで file_get_contents はHTTPヘッダに "User-Agent: OreOreAgent" を付与する。

24
22
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
24
22