Demonstrates listing roles.

## Explore further


For detailed documentation that includes this code sample, see the following:

- [Create and manage custom roles](https://docs.cloud.google.com/iam/docs/creating-custom-roles.md.txt)

## Code sample

### C++


To learn how to install and use the client library for IAM, see
[IAM client libraries](https://docs.cloud.google.com/iam/docs/reference/libraries.md.txt).


For more information, see the
[IAM C++ API
reference documentation](https://docs.cloud.google.com/cpp/docs/reference/iam/latest).


To authenticate to IAM, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```c++
namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& project) {
  iam::IAMClient client(iam::MakeIAMConnection());
  int count = 0;
  google::iam::admin::v1::ListRolesRequest request;
  request.set_parent(project);
  for (auto& role : client.ListRoles(request)) {
    if (!role) throw std::move(role).status();
    std::cout << "Roles successfully retrieved: " << role->name() << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No roles found in project: " << project << "\n";
  }
}
```

### C#


To learn how to install and use the client library for IAM, see
[IAM client libraries](https://docs.cloud.google.com/iam/docs/reference/libraries.md.txt).


For more information, see the
[IAM C# API
reference documentation](https://developers.google.com/api-client-library/dotnet/apis/iam/v1).


To authenticate to IAM, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```c#

using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class CustomRoles
{
    public static IList<Role> ListRoles(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var response = service.Projects.Roles.List("projects/" + projectId)
            .Execute();
        foreach (var role in response.Roles)
        {
            Console.WriteLine(role.Name);
        }
        return response.Roles;
    }
}
```

### Go


To learn how to install and use the client library for IAM, see
[IAM client libraries](https://docs.cloud.google.com/iam/docs/reference/libraries.md.txt).


For more information, see the
[IAM Go API
reference documentation](https://pkg.go.dev/cloud.google.com/go/iam/admin/apiv1).


To authenticate to IAM, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```go
import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// listRoles lists a project's roles.
func listRoles(w io.Writer, projectID string) ([]*iam.Role, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	response, err := service.Projects.Roles.List("projects/" + projectID).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.Roles.List: %w", err)
	}
	for _, role := range response.Roles {
		fmt.Fprintf(w, "Listing role: %v\n", role.Name)
	}
	return response.Roles, nil
}
```

### Java


To learn how to install and use the client library for IAM, see
[IAM client libraries](https://docs.cloud.google.com/iam/docs/reference/libraries.md.txt).


For more information, see the
[IAM Java API
reference documentation](https://developers.google.com/api-client-library/java/apis/iam/v1).


To authenticate to IAM, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```java

import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.cloud.iam.admin.v1.IAMClient.ListRolesPagedResponse;
import com.google.iam.admin.v1.ListRolesRequest;
import java.io.IOException;

/** List roles in a project. */
public class ListRoles {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variable before running the sample.
    String projectId = "your-project-id";

    listRoles(projectId);
  }

  public static void listRoles(String projectId) throws IOException {
    ListRolesRequest listRolesRequest =
        ListRolesRequest.newBuilder().setParent("projects/" + projectId).build();

    // Initialize client for sending requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (IAMClient iamClient = IAMClient.create()) {
      ListRolesPagedResponse listRolesResponse = iamClient.listRoles(listRolesRequest);
      listRolesResponse.iterateAll().forEach(role -> System.out.println(role));
    }
  }
}
```

### Python


To learn how to install and use the client library for IAM, see
[IAM client libraries](https://docs.cloud.google.com/iam/docs/reference/libraries.md.txt).


For more information, see the
[IAM Python API
reference documentation](https://developers.google.com/api-client-library/python/apis/iam/v1).


To authenticate to IAM, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment.md.txt).

```python
from google.cloud.iam_admin_v1 import IAMClient, ListRolesRequest, RoleView
from google.cloud.iam_admin_v1.services.iam.pagers import ListRolesPager


def list_roles(
    project_id: str, show_deleted: bool = True, role_view: RoleView = RoleView.BASIC
) -> ListRolesPager:
    """Lists IAM roles in a GCP project.

    Args:
        project_id: GCP project ID
        show_deleted: Whether to include deleted roles in the results
        role_view: Level of detail for the returned roles (e.g., BASIC or FULL)

    Returns: A pager for traversing through the roles
    """

    client = IAMClient()
    parent = f"projects/{project_id}"
    request = ListRolesRequest(parent=parent, show_deleted=show_deleted, view=role_view)
    roles = client.list_roles(request)
    for page in roles.pages:
        for role in page.roles:
            print(role)
    print("Listed all iam roles")
    return roles
```

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples.md.txt?product=identityandaccessmanagement).