---
title: Generate Password
description: The Generate Password extended operation uses the POST /directory/v1/suggestPassword endpoint. This endpoint uses suggestPassword instead of generatePassword since the request doesn't make a backend change to the password of a target entry.
component: pingdirectory
page_id: pingdirectory:directory:extended-operations/generate-password/generate-password
canonical_url: https://developer.pingidentity.com/pingdirectory/directory/extended-operations/generate-password/generate-password.html
section_ids:
  request-body: Request body
  response-body: Response body
  headers: Headers
  body: Body
  example-request: Example Request
  example-response: Example Response
---

# Generate Password

##

```none
POST {{apiPath}}/directory/v1/suggestPassword
```

The Generate Password extended operation uses the `POST /directory/v1/suggestPassword` endpoint. This endpoint uses `suggestPassword` instead of `generatePassword` since the request doesn't make a backend change to the password of a target entry.

### Request body

The request body for this method can only contain one of the following attributes:

* `passwordPolicyDN`

  An optional parameter whose value is the DN of the password policy whose password generator should be used to generate the suggested passwords.

* `targetEntryDN`

  An optional parameter whose value is the DN of the user for whom the suggested passwords will be generated.

If neither of the above attributes are specified, the password generator for the server's default password policy will be used to generate the passwords.

The following request body attributes are fully optional:

* `numberOfPasswords`

  An optional integer parameter whose value is the number of suggested passwords to generate. If specified, the value must be greater than or equal to one.

* `validationAttempts`

  An optional integer parameter whose value is the maximum number of attempts for each suggested password that the server should make to generate a password that satisfies all of the password validators configured for the selected password policy. If specified, the value must be greater than or equal to zero.

* `_controls`

  An optional array of JSON-formatted request controls used to process the generate password request. These controls are narrowed down based on which conversions from JSON to LDAP are currently implemented by the Directory REST API. The following request controls are supported and relevant to the generate password request:

  * [Operation Purpose Request Control](../../controls/operation-purpose-request-control.html)

  * [Intermediate Client Request Control](../../controls/intermediate-client-request-control.html)

  * [Intermediate Client Response Control](../../controls/intermediate-client-response-control.html)

### Response body

Upon a successful operation where the HTTP status code is `200`, the following fields will be included in the JSON object:

* `resultCode`

  A required JSON object that contains the following fields:

  * `value`

    The integer value for the LDAP result code.

  * `name`

    A name for the LDAP result code.

* `passwordPolicyDN`

  An optional string field whose value is the DN of the password policy whose password generator was used to create the suggested passwords. This field is present in a successful response and absent otherwise.

* `suggestedPasswords`

  An optional array of JSON objects that contain the suggested passwords. Each JSON object should contain the following fields:

  * `suggestedPassword`

    A string field whose value will be the suggested password. This field will always be present.

  * `validationAttempted`

    A Boolean field that indicates whether the server made an attempt to ensure that the suggested password passes validation.

  * `validationErrors`

    An optional string array field whose values are reasons that the suggested password would not be acceptable to the password validators configured for the associated password policy. If `validationAttempted` is true and `validationErrors` is empty, then the suggested password passed validation.

The following optional fields will be include if they are populated by the underlying LDAP operation, but are otherwise omitted:

* `matchedDN`

  A string field that holds the matched DN for the operation, if appropriate. You can omit this if no matched DN value is needed or appropriate.

* `diagnosticMessage`

  A string field that holds a human-readable message with additional information about the operation. You can omit this if no diagnostic message is needed or appropriate.

* `_controls`

  An optional array of JSON-formatted response controls if they are generated in response to a request control. Note that some request controls do not have corresponding response controls.

### Headers

Authorization      Bearer {{accessToken}}

Content-Type      application/json

### Body

raw ( application/json )

```json
{
    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
    "numberOfPasswords": 2,
    "validationAttempts": 5
}
```

##

### Example Request

* cURL

* C#

* Go

* HTTP

* Java

* jQuery

* NodeJS

* Python

* PHP

* Ruby

* Swift

```shell
curl --location --globoff '{{apiPath}}/directory/v1/suggestPassword' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {{accessToken}}' \
--data '{
    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
    "numberOfPasswords": 2,
    "validationAttempts": 5
}'
```

```csharp
var options = new RestClientOptions("{{apiPath}}/directory/v1/suggestPassword")
{
  MaxTimeout = -1,
};
var client = new RestClient(options);
var request = new RestRequest("", Method.Post);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer {{accessToken}}");
var body = @"{" + "\n" +
@"    ""passwordPolicyDN"": ""cn=Default Password Policy,cn=Password Policies,cn=config""," + "\n" +
@"    ""numberOfPasswords"": 2," + "\n" +
@"    ""validationAttempts"": 5" + "\n" +
@"}";
request.AddStringBody(body, DataFormat.Json);
RestResponse response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);
```

```golang
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io"
)

func main() {

  url := "{{apiPath}}/directory/v1/suggestPassword"
  method := "POST"

  payload := strings.NewReader(`{
    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
    "numberOfPasswords": 2,
    "validationAttempts": 5
}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Content-Type", "application/json")
  req.Header.Add("Authorization", "Bearer {{accessToken}}")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := io.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

```http
POST /directory/v1/suggestPassword HTTP/1.1
Host: {{apiPath}}
Content-Type: application/json
Authorization: Bearer {{accessToken}}

{
    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
    "numberOfPasswords": 2,
    "validationAttempts": 5
}
```

```java
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n    \"passwordPolicyDN\": \"cn=Default Password Policy,cn=Password Policies,cn=config\",\n    \"numberOfPasswords\": 2,\n    \"validationAttempts\": 5\n}");
Request request = new Request.Builder()
  .url("{{apiPath}}/directory/v1/suggestPassword")
  .method("POST", body)
  .addHeader("Content-Type", "application/json")
  .addHeader("Authorization", "Bearer {{accessToken}}")
  .build();
Response response = client.newCall(request).execute();
```

```javascript
var settings = {
  "url": "{{apiPath}}/directory/v1/suggestPassword",
  "method": "POST",
  "timeout": 0,
  "headers": {
    "Content-Type": "application/json",
    "Authorization": "Bearer {{accessToken}}"
  },
  "data": JSON.stringify({
    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
    "numberOfPasswords": 2,
    "validationAttempts": 5
  }),
};

$.ajax(settings).done(function (response) {
  console.log(response);
});
```

```javascript
var request = require('request');
var options = {
  'method': 'POST',
  'url': '{{apiPath}}/directory/v1/suggestPassword',
  'headers': {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer {{accessToken}}'
  },
  body: JSON.stringify({
    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
    "numberOfPasswords": 2,
    "validationAttempts": 5
  })

};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});
```

```python
import requests
import json

url = "{{apiPath}}/directory/v1/suggestPassword"

payload = json.dumps({
  "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
  "numberOfPasswords": 2,
  "validationAttempts": 5
})
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer {{accessToken}}'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
```

```php
<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('{{apiPath}}/directory/v1/suggestPassword');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
$request->setHeader(array(
  'Content-Type' => 'application/json',
  'Authorization' => 'Bearer {{accessToken}}'
));
$request->setBody('{\n    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",\n    "numberOfPasswords": 2,\n    "validationAttempts": 5\n}');
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}
```

```ruby
require "uri"
require "json"
require "net/http"

url = URI("{{apiPath}}/directory/v1/suggestPassword")

http = Net::HTTP.new(url.host, url.port);
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request["Authorization"] = "Bearer {{accessToken}}"
request.body = JSON.dump({
  "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
  "numberOfPasswords": 2,
  "validationAttempts": 5
})

response = http.request(request)
puts response.read_body
```

```swift
let parameters = "{\n    \"passwordPolicyDN\": \"cn=Default Password Policy,cn=Password Policies,cn=config\",\n    \"numberOfPasswords\": 2,\n    \"validationAttempts\": 5\n}"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string: "{{apiPath}}/directory/v1/suggestPassword")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer {{accessToken}}", forHTTPHeaderField: "Authorization")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
  guard let data = data else {
    print(String(describing: error))
    return
  }
  print(String(data: data, encoding: .utf8)!)
}

task.resume()
```

### Example Response

200 OK

```json
{
    "resultCode": {
        "value": 0,
        "name": "success"
    },
    "passwordPolicyDN": "cn=Default Password Policy,cn=Password Policies,cn=config",
    "suggestedPasswords": [
        {
            "suggestedPassword": "GarnishHayekElixirNortheastern",
            "validationAttempted": false
        },
        {
            "suggestedPassword": "CrawdadMechanicApotheosisEnvironment",
            "validationAttempted": false
        }
    ]
}
```
