Azure FunctionsのAPIは、POSTメソッドだけでなくGETメソッドも利用することができる。
今回は、以前作成したプログラムのPOSTメソッドをGETメソッドに変更し、Postmanによる呼び出しもしてみたので、その内容を共有する。
前提条件
下記記事の実装が完了していること。
また、以下の記事のPostmanをインストール済であること。
やってみたこと
- 作成したサンプルプログラム(App Service側)の内容
 - 作成したサンプルプログラム(Azure Functions側)の内容
 - API Management上のAzure Functionsの変更
 - 作成したサンプルプログラムの実行結果(API Management利用後)
 - ローカル環境でのAzure FunctionsのAPI呼出し
 - Azure環境でのAzure FunctionsのAPI呼出し
 
作成したサンプルプログラム(App Service側)の内容
作成したサンプルプログラム(App Service側)の構成は以下の通り。
 
 なお、上記の赤枠は、前提条件のプログラムから変更したプログラムである。
コントローラクラスの内容は以下の通りで、callFunctionApi関数の呼び出しがGETメソッドで、リクエストパラメータを渡す形に変更している。
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
public class DemoController {
    /** RestTemplateオブジェクト */
    @Autowired
    private RestTemplate restTemplate;
    /** ObjectMapperオブジェクト */
    @Autowired
    private ObjectMapper objectMapper;
    /** application.propertiesからdemoAzureFunc.urlBaseの値を取得 */
    @Value("${demoAzureFunc.urlBase}")
    private String demoAzureFuncBase;
    /**
     * メイン画面を初期表示する.
     * @return メイン画面
     */
    @GetMapping("/")
    public String index() {
        return "main";
    }
    /**
     * Azure FunctionsのcallFunctionApi関数呼出処理.
     * @param model Modelオブジェクト
     * @return 次画面
     */
    @RequestMapping("/callFunction")
    public String callFunction(Model model) {
        // Azure FunctionsのcallFunctionApi関数を呼び出す
        ResponseEntity<String> response = restTemplate.exchange(demoAzureFuncBase 
            + "callFunctionApi?param=DemoController_callFunction_calling"
             , HttpMethod.GET, null, String.class);
        // callFunctionApi関数の呼出結果を設定する
        SearchResult searchResult = null;
        try {
            searchResult = objectMapper.readValue(
                response.getBody(), SearchResult.class);
            if (searchResult != null) {
                model.addAttribute("result", searchResult.getResult());
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return "next";
    }
    /**
     * メイン画面に戻る処理.
     * @return メイン画面
     */
    @PostMapping("/backToMain")
    public String backToMain() {
        return "main";
    }
    /**
     * エラー画面に遷移する処理.
     * @return エラー画面
     */
    @RequestMapping("/toError")
    public String toError() {
        return "error";
    }
}その他のソースコード内容は、以下のサイトを参照のこと。
 https://github.com/purin-it/azure/tree/master/azure-functions-postman-get/demoAzureApp
 
 
作成したサンプルプログラム(Azure Functions側)の内容
作成したサンプルプログラム(Azure Functions側)の構成は以下の通り。
 
 なお、上記の赤枠は、前提条件のプログラムから変更したプログラムである。
ハンドラークラスの内容は以下の通りで、callFunctionApi関数の呼び出しがGETメソッドで、リクエストパラメータを受け取る形に変更している。
package com.example;
import java.util.Optional;
import org.springframework.cloud.function.adapter.azure.FunctionInvoker;
import com.example.model.SearchParam;
import com.example.model.SearchResult;
import com.microsoft.azure.functions.ExecutionContext;
import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;
public class CallFunctionApiHandler 
    extends FunctionInvoker<SearchParam, SearchResult> {
    /**
     * HTTP要求に応じて、DemoAzureFunctionクラスのcallFunctionApiメソッドを呼び出し、
     * その戻り値をボディに設定したレスポンスを返す.
     * @param request リクエストオブジェクト
     * @param context コンテキストオブジェクト
     * @return レスポンスオブジェクト
     */
    @FunctionName("callFunctionApi")
    public HttpResponseMessage execute(
            @HttpTrigger(name = "request"
                , methods = HttpMethod.GET, authLevel = AuthorizationLevel.ANONYMOUS) 
                    HttpRequestMessage<Optional<String>> request,
            ExecutionContext context) {
        // リクエストパラメータ値を取得し、検索用パラメータに設定する
        SearchParam searchParam = new SearchParam();
        searchParam.setParam(request.getQueryParameters().get("param"));
        // handleRequestメソッド内でDemoAzureFunctionクラスのcallFunctionApiメソッド
        // を呼び出し、その戻り値をボディに設定したレスポンスを、JSON形式で返す
        return request.createResponseBuilder(HttpStatus.OK)
             .body(handleRequest(searchParam, context))
             .header("Content-Type", "text/json").build();
    }
}その他のソースコード内容は、以下のサイトを参照のこと。
 https://github.com/purin-it/azure/tree/master/azure-functions-postman-get/demoAzureFunc
 
 
API Management上のAzure Functionsの変更
Azure FunctionsのAPIを、POSTメソッドからGETメソッドに変更したため、API Management上のAzure Functionsを削除し再作成する。その手順は、以下の通り。
1) 作成済のAzure FunctionsのAPIメニューを選択し、「Delete(削除)」を選択する。
 
2) APIを削除してよいかどうかの確認ダイアログが表示されるため、「Yes」ボタンを押下する。
 
3) 削除が完了し、以下のように右上に完了メッセージが表示されることが確認できる。
 
また、作成手順については、以下の記事の「Azure FunctionsのAPI Managementへの追加」を参照のこと。
 
 
作成したサンプルプログラムの実行結果(API Management利用後)
作成したサンプルプログラムの実行結果(API Management利用後)は、以下の通り。
1) Azure App ServiceのURL「https://azureappdemoservice.azurewebsites.net/」とアクセスすると以下の画面が表示されるため、「ファンクション呼び出し」ボタンを押下する。
 
 なお、上記URLは、下記Azure App ServiceのURLから確認できる。
 
2) callFunctionApi関数が呼び出され、以下の画面に遷移する。その後「戻る」ボタンを押下する。
 
 なお、App Serviceのapplication.propertiesを以下の設定にした状態で、Azure上に、Azure App Service, Azure Functionsのプログラムをデプロイし、実行している。
 
また、Azure App Serviceにデプロイする過程は、以下の記事の「App ServiceへのSpring Bootを利用したJavaアプリケーションのデプロイ」を参照のこと。
さらに、Azure Functionsにデプロイする過程は、以下の記事の「Azure FunctionsへのSpring Bootを利用したJavaアプリケーションのデプロイ」を参照のこと。
 
 
ローカル環境でのAzure FunctionsのAPI呼出し
Postmanを利用して、ローカル環境でのAzure FunctionsのAPI呼出し内容を設定し実行する手順は、以下の通り。
1) Azure Functionsをローカルで実行するため、「mvn azure-functions:run」を実行する。そうすると、ローカル環境で実行する場合、Azure Functions APIのURLは「http://localhost:7071/api/callFunctionApi」であることが確認できる。
 
なお、Azure Functionsのデプロイ・実行手順は、以下の記事の「Spring Bootを利用したJavaアプリケーションのローカル環境での実行」を参照のこと。
2) Postmanを起動し、ローカル環境で実行する場合のAzure Functions APIのURL「http://localhost:7071/api/callFunctionApi」を指定する。
 
3) Query Paramsにリクエストパラメータの値を指定する。そうすると、URLにもリクエストパラメータが追加されることが確認できる。この状態で「Send」ボタンを押下する。
 
4) 指定したAPIが呼び出され、以下のように、レスポンスが画面下に表示されることが確認できる。
 
 
 
Azure環境でのAzure FunctionsのAPI呼出し
Azure環境でのAzure FunctionsやAPI ManagementのAPIも、Postmanを利用して実行できる。その結果は、以下の通り。
1) Azure環境でのAzure FunctionsのAPIを呼び出すには、以下のようにURL・リクエストパラメータを設定し、「Send」ボタンを押下する。
 
2) 指定したAPIが呼び出され、以下のように、レスポンスが画面下に表示されることが確認できる。
 
 なお、このとき指定するAPIの「https://azurefuncdemoapp.azurewebsites.net」の部分は、Azure Portal上のAzure FunctionsのURLから確認できる。
 
3) Azure環境でのAPI Management経由でAzure FunctionsのAPIを呼び出すには、以下のようにURL・リクエストパラメータを設定し、「Send」ボタンを押下する。
 
4) 指定したAPIが呼び出され、以下のように、レスポンスが画面下に表示されることが確認できる。
 
 なお、このとき指定するAPIの「https://azureapipurinit.azure-api.net/azureFuncDemoApp」の部分は、Azure Portal上のAPI Managementの「BaseURL」から確認できる。
 
要点まとめ
- Azure FunctionsのAPIは、POSTメソッドだけでなくGETメソッドも利用でき、Postmanによる呼び出しも行える。
 






