5
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.

PHPのビルトインサーバーでAPIモックを楽に作ってDocker化

Last updated at Posted at 2018-08-17

APIモックサーバーを作りたいなと思ってたら、PHPで楽に作れると見たので試してみる。

PHP5.4から組み込まれたビルドインWebサーバが便利らしい、今回はこれで作る!

環境

macOS 10.12.6

$ php -v
PHP 5.6.30 (cli) (built: Oct 29 2017 20:30:32)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

実装

シンプルに書く

php
<?php
$response = [
  'id'=> 1,
  'memo' => 'mock api memo',
];
header('Content-Typej: application/json; charset=utf-8');
echo json_encode($response);

以下コマンドでサーバー起動

$ php -S localhost:8000

GETレスポンス

{"id":1,"memo":"mock api memo"}

おおできた、本当にすげえ簡単に作れる

実装 パス対応

http://localhost:8000/memo/100

のようにmemo/100というパスへのアクセスに対応する

php
<?php
if (!preg_match('#\A/memo/(?P<id>\d+)\z#', $_SERVER['PATH_INFO'], $matches)) {
  header('HTTP/1.1 404 Not Found');
}
$response = [
  'id'=> (int)$matches['id'],
  'memo' => 'memo' . $matches['id'],
];
header('Content-Typej: application/json; charset=utf-8');
echo json_encode($response);

http://localhost:8000/memo/100のレスポンス

{"id":100,"memo":"memo100"}

これまた簡単にできた、素晴らしい

試しにPOST

$ curl -X POST http://localhost:8000/memo/100
{"id":100,"memo":"memo100"}

あれ、普通にレスポンスが返ってきた

特に指定しなければ何でも受け付けるのね

Docker化

Dockerfileを作成

FROM php:5.6-alpine3.7
WORKDIR /workspace
EXPOSE 8000
CMD ["php","-S","0.0.0.0:8000"]

docker-compose.ymlを作成

version: '3'
services:
  php-api-mock-sample:
    build: .
    volumes:
      - .:/workspace/
    ports:
      - "8000:8000"

ファイル構成

.
├── Dockerfile
├── docker-compose.yml
└── index.php

Docker化開始

$ docker-compose build
$ docker-compose up

以下にアクセス

jsonレスポンスが返ってきたらOK

5
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
5
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?