REST API Best Practices
You Give REST a Bad Name
/** @OA\Get(security={{ "bearerAuth": {} }}, tags={"TAG"},
* path="/comments/{id}", summary="DESCRIPTION",
* @OA\Parameter(name="id", in="path", required=true, description="DESCRIPTION", example="1",),
* @OA\Parameter(name="Accept-Language", in="header", description="DESCRIPTION", example="ru",),
* @OA\Parameter(name="group_id", in="query", description="DESCRIPTION", example="1",),
* @OA\Parameter(name="status", in="query", description="DESCRIPTION",
* @OA\Schema(type="array",
* @OA\Items(type="string", enum={"available", "pending", "sold"}, default="available"),
* ),
* ),
* @OA\Parameter(name="groups", in="query", description="DESCRIPTION",
* @OA\Schema(type="array",
* @OA\Items(type="string"),
* ),
* ),
*
* @OA\RequestBody(required=true,
* @OA\MediaType(mediaType="application/json",
* @OA\Schema(example={"id":1}),
* ),
* @OA\MediaType(mediaType="application/xml",
* @OA\Schema(ref="#/components/schemas/Model",),
* ),
* @OA\MediaType(mediaType="multipart/form-data",
* @OA\Schema(
* @OA\Property(property="name", description="name", example="name"),
* @OA\Property(property="image", description="file", type="string", format="binary"),
* @OA\Property(property="images[]", description="files array", type="array",
* @OA\Items(type="string", format="binary"),
* ),
* ),
* ),
* ),
* @OA\Response(response=200, description="Success",),
* @OA\Response(response=401, description="Error: Unauthorized"),
* )
*/
Как описать свое апи
swagger-php - Generate interactive OpenAPI documentation for your RESTful API using doctrine annotations.
То что нужно для описания. Пишем код как обычно но там где просходит обращение к апи пишем аннотации.
Чтобы создать документацию нужна главная аннотация
/**
* @OA\Info(version="1.0.0", title="My OpenApi", description="My OpenApi description" )
*/
Создаем вкладки для группировки методов:
/**
* @OA\Tag(name="comment", description="Here you can find public api methods comments resource", )
*/
Некоторые методы будут защищены авторизацией. Обычно это bearerAuth, то есть в заголовках будет передаваться токен доступа. Для активации нужно добавить:
/**
* @OA\SecurityScheme(securityScheme="bearerAuth", in="header", name="bearerAuth", type="http", scheme="bearer", bearerFormat="JWT", ),
*/
API
Схема модели:
/**
* @OA\Schema(schema="Comment", description="Comment model", title="Comment model", required={"text"},),
* @OA\Property(property="text", description="Comment text", type="string",),
* @OA\Property(property="post_id", description="post id", type="integer",),
* @OA\Property(property="parent_id", description="comment id", type="integer",),
*
* @OA\RequestBody(request="Comment", description="Comment request", required=true,
* @OA\JsonContent(ref="#/components/schemas/Comment"),
* )
*/
Круд для апи ресурса:
/**
* @OA\get(path="/comments", tags={"comment"}, summary="get all comment",
* @OA\Response(response=200, description="ok",
* @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/Comment"),),
* ),
* )
*/
/**
* @OA\get(path="/comments/{id}", tags={"comment"}, summary="get comment", security={ {"bearerAuth"} },
* @OA\Parameter(name="id", in="path", required=true, description="comment id",),
* @OA\Response(response=200, ref="#/components/requestBodies/Comment",),
* )
*/
/**
* @OA\post(path="/comments", tags={"comment"}, summary="store comment", security={ {"bearerAuth"} },
* @OA\Parameter(name="text", in="query", required=true, description="comment text",),
* @OA\Parameter(name="post_id", in="query", required=true, description="post id",),
* @OA\Parameter(name="parent_id", in="query", required=true, description="parent comment",),
* @OA\Response(response=200, description="ok", ref="#/components/schemas/Comment",),
* @OA\Response(response=405, description="Validation exception"),
* )
*/
/**
* @OA\put(path="/comments/{id}", tags={"comment"}, summary="update comment", security={ {"bearerAuth"} },
* requestBody={"$ref": "#/components/requestBodies/Comment"},
* @OA\Parameter(name="id", in="path", required=true, description="comment id",),
* @OA\Response(response=200, description="ok"),
* @OA\Response(response=400, description="Invalid id supplied"),
* @OA\Response(response=405, description="Validation exception"),
* )
*/
/**
* @OA\delete(path="/comments/{id}", tags={"comment"}, summary="delete comment", security={ {"bearerAuth"} },
* @OA\Parameter(name="id", in="path", required=true, description="comment id",),
* @OA\Response(response=200, description="ok"),
* )
*/
Для ларавел есть обертка для этой либы.
Пример описания. Ставим для ларавел пакет `composer require swagger-api/swagger-ui`
Перед генерацией нужно добавить описание апи (можно описанное выше). Затем выпоняем:
php artisan l5-swagger:generate
теперь смотрим http://localhost:8000/api/documentation
FAQ
Если на nginx `api/documentation` не открывается попробуй добавить в конфиг:
# nginx config fix
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
try_files $uri /index.php;
access_log off;
expires 365d;
}