Search code examples
javamicrosoft-graph-apimicrosoft-graph-sdks

Microsoft Graph SDK for Java - check if user photo exists


I can currently successfully retrieve a user photo (user/photo/content) via the Microsoft Graph SDK for Java. If I use the API (user/photo), an Microsoft.Fast.Profile.Core.Exception.ImageNotFoundException is thrown. Unfortunately, I am missing a way to check if a photo exists at all. The photo property on the user object (API: /user ->user.getPhoto()) is always null. I find that very bad and illogical.

Has anyone implemented this successfully before or has an idea?

            var user = graphClient.users().byUserId(user.getId()).get();
            var photo = graphClient.users().byUserId(user.getId()).photo().get(); // photo meta data

        //  if(user.getPhoto() != null)  // always null, even tried with expand user.photo;
            if (photo != null) { // throws exception if photo is empty
                var photoStream = graphClient.users().byUserId(user.getId()).photo().content().get(); // works and is filled
                byte[] photoBytes = photoStream.readAllBytes();
                photoStream.read(photoBytes);
                var base64Photo = Base64.getEncoder().encodeToString(photoBytes);
                System.out.println(base64Photo);

                if (photo.getAdditionalData().containsKey(MEDIA_CONTENT_TYPE)) {
                    var mimeType = photo.getAdditionalData().get(MEDIA_CONTENT_TYPE);
                    System.out.println(mimeType);
                }
            }

Solution

  • First of all, user resource doesn't allow to expand photo. You need to make a call for each user

    var photo = graphClient.users().byUserId(user.getId()).photo().get();
    

    The current behavior of the endpoint is that if no photo exists, the operation returns 404 Not Found.

    You need to handle a not found error

    try {
        var photo = graphClient.users().byUserId(user.getId()).photo().get();
    } catch (ODataError e) {
        if (e.getResponseStatusCode() == 404 && e.getError().getCode() == "ImageNotFound" ){ // photo not exist
        // add photo
        }
        System.out.println(e.getMessage());
    }