A web app that calls web APIs: Call a web API

Now that you have a token, you can call a protected web API. You usually call a downstream API from the controller or pages of your web app.

Call a protected web API

Calling a protected web API depends on your language and framework of choice:

private String getUserInfoFromGraph(String accessToken) throws Exception {
    // Microsoft Graph user endpoint
    URL url = new URL("https://microsoftgraph.chinacloudapi.cn/v1.0/me");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // Set the appropriate header fields in the request header.
    conn.setRequestProperty("Authorization", "Bearer " + accessToken);
    conn.setRequestProperty("Accept", "application/json");

    String response = HttpClientHelper.getResponseStringFromConn(conn);

    int responseCode = conn.getResponseCode();
    if(responseCode != HttpURLConnection.HTTP_OK) {
        throw new IOException(response);
    }

    JSONObject responseObject = HttpClientHelper.processResponse(responseCode, response);
    return responseObject.toString();
}

Next steps

  • Learn more by building an ASP.NET Core web app that signs in users in the following multi-part tutorial series

  • Explore Microsoft identity platform web app samples