サンプルで生成されたソースを読む。この程度なら、全部、ブラウザ操作でできる。何もダウンロード、ユーザ登録する必要はない。
https://editor.swagger.io/ へ行く。ペットショップのサンプルがある。ブラウザで操作できる。user, order などを消して、 pet の post/get だけにする。
文法エラーがあると、警告が出る。
generate client=> java
generate server => jaxrs
すると、画面の yaml に対応する java ソースが、ダウンロードされる。pom.xml に、 jetty 他の依存が書いてあるので、ビルドすると、サーバを持ってくるのだろう。
swagger.yaml
/pet/{petId}:
get:
operationId: "getPetById" <=この関数名になる。
produces:
- "application/json"
parameters:
- name: "petId" <=引数になる。パスから得る。
type: "integer"
responses:
200:
schema:
$ref: "#/definitions/Pet" <=これを返す。
クライアントのスタブ
java-client/src/main/java/io/swagger/client/api/PetApi.java
public Pet getPetById(Long petId) throws ApiException {
ApiResponse<Pet> resp = getPetByIdWithHttpInfo(petId);
return resp.getData();
}
ここから、getPetByIdValidateBeforeCall=>getPetByIdCall に行く。
public com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
String localVarPath = "/pet/{petId}"
.replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString()));
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
は、要するに、 url に、 query string, form を付けて、 http を出すだけ。
サーバのスタブ
これが、 jax のアノテーションによって、 url を受けるところ。
jaxrs-server/src/gen/java/io/swagger/api/PetApi.java
public class PetApi {
private final PetApiService delegate;
delegate = PetApiServiceFactory.getPetApi();
@GET
@Path("/{petId}")
@Produces({ "application/json" })
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class),
})
petId は、整数引数で与えられる。
public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId
,@Context SecurityContext securityContext)
throws NotFoundException {
return delegate.getPetById(petId,securityContext);
}
delegate の実体は、抽象クラス
jaxrs-server/src/gen/java/io/swagger/api/PetApiService.java
public abstract class PetApiService {
public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException;
これが、実装クラス。
jaxrs-server/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java
public class PetApiServiceImpl extends PetApiService {
public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException {
// do some magic!
return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build();
}
new Pet.class は、どこでやっているんだ?
以上