# Create User Consents
source: https://developer.mastercard.com/consent-management/documentation/tutorials-and-guides/user-consents-tutorial/create-consents/index.md

## Overview {#overview}

This step creates a user-based consent by calling `POST /consents` with user identity details and an `insights` consent type. Unlike card-based consent, user-based consent does not require 3DS authentication --- the consent is approved immediately.

## Enter User Details {#enter-user-details}

When the reference app is running, open <http://localhost:8081> and select **User Consent Management API**. The form displays fields for full name, postal code, email, and phone number.

![User Consent Management API form with user detail fields](https://static.developer.mastercard.com/content/consent-management/img/ref-app-user-consent.png)

The `postalCode` field is required. The `email` and `phone` fields are optional and are included as identity objects if provided.

Complete the form and select **Create Consent** to submit.

## Create User Consent Request {#create-user-consent-request}

When the form is submitted, the reference app calls its own `/create-user-consent` endpoint, which sends a `POST /consents` request to the Consent Management \& Enrollment API.
* Java
* Python

```java
// ConsentsController.java

  @PostMapping("/create-user-consent")
  public String postConsents(UserDetails userDetails, Model model,
      @RequestParam(required = false) String email,
      @RequestParam(required = false) String phone) {

    ConsentsCreate request = new ConsentsCreate();
    List<Identity> identities = new ArrayList<>();
    if (email != null && !email.isBlank()) {
      identities.add(new Identity().type("EMAIL").value(email));
    }
    if (phone != null && !phone.isBlank()) {
      identities.add(new Identity().type("PHONE").value(phone));
    }
    userDetails.setIdentities(identities.isEmpty() ? null : identities);
    request.setUserDetails(userDetails);
    ConsentCreate consent = new ConsentCreate();
    consent.setName("insights");
    request.setConsents(Collections.singletonList(consent));

    try {
      Consents response = apiService.getApiClient().createConsents(request);
      log.info("Consent Token: " + response.getConsentToken());
      this.consentToken = response.getConsentToken();
      model.addAttribute("consentToken", this.consentToken);
      return "consents-info";
    } catch (ApiException e) {
      model.addAttribute(ERROR_MSG, e.getResponseBody());
    } catch (Exception e) {
      model.addAttribute(ERROR_MSG, e.getMessage());
    }

    return ERROR_TEMPLATE;
  }
```

```python
@app.route("/create-user-consent", methods=['GET', 'POST'])
def create_user_consents():

    if request.method == 'POST':

        identities = []

        if request.form.get("email"):
            identities.append({
                "type": "EMAIL",
                "value": request.form["email"],
                "verified": False
            })

        if request.form.get("phone"):
            identities.append({
                "type": "PHONE",
                "value": request.form["phone"],
                "verified": False
            })

        session["test_user_details"] = {
            "fullName": request.form["fullName"],
            "postalCode": request.form["postalCode"],
            "identities": identities,
        }

        try:
            resp = api_create_user_consent(session["test_user_details"])
            session["consent_token"] = resp["consentToken"]
            return redirect(url_for('consents_info'))

        except:
            error_msg = resp
            return render_template('error.html', error_msg=error_msg)

    return render_template('create-user-consent.html')
```

The reference app maps the form fields to a `userDetails` object with the `fullName`, `postalCode`, and optional `identities` array. The consent type is set to `insights`.

### Sample Request {#sample-request}

```json
{
  "consents": [
    {
      "name": "insights",
      "details": {}
    }
  ],
  "userDetails": {
    "fullName": "John Smith",
    "postalCode": "50210-1234",
    "identities": [
      {
        "type": "EMAIL",
        "value": "john333@somemail.com",
        "verified": false
      },
      {
        "type": "PHONE",
        "value": "+11234567898",
        "verified": false
      }
    ]
  }
}
```

## API Response {#api-response}

A successful response returns a `consentToken` and a list of consents with status `APPROVED`.

```json
{
  "cardReference": null,
  "consentToken": "CBCU-2xxx2bd4-31a5-4e14-8abb-4245b3f48f4a",
  "auth": null,
  "consents": [
    {
      "id": "12853700402",
      "status": "APPROVED",
      "name": "insights",
      "details": {},
      "expiryDate": "2025-11-11T11:42:04.596Z"
    }
  ]
}
```

The `consentToken` is a unique identifier for the user. Store this token securely. It is required for:

* **Retrieving consents** : Call `GET /consents/{consentToken}` to list the user's consents.
* **Revoking consents** : Call `DELETE /consents/{consentToken}/consents/{consentId}` to revoke a specific consent, or `DELETE /consents/{consentToken}` to revoke all consents.
* **Updating user details** : Include the `consentToken` in the `userDetails` object when calling `POST /consents`. The system recognizes the existing user and updates their information.

## Get Consents {#get-consents}

To retrieve the consents associated with the user, select **Get User Consents** on the **Consents** info page. The reference app calls `GET /consents/{consentToken}` and displays each consent in a list.

### Implementation {#implementation}

* Java
* Python

```java
// ConsentsController.java

  @GetMapping("/getConsents")
  public ResponseEntity<Consents> getConsents(@RequestParam String reference) {
    try {
      Consents consents = apiService.getApiClient().getConsents(reference);
      return new ResponseEntity<>(consents, HttpStatus.OK);
    } catch (Exception e) {
      log.error(e.getMessage());
    }
    return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
  }
```

```python
@app.route("/getConsents")
def get_consents():
    reference = request.args.get('reference')
    resp = api_get_consents(reference)
    return resp
```

### Response {#response}

The response contains the `consentToken` and a `consents` array. Each consent includes an `id`, `status`, `name`, and `expiryDate`.

```json
{
  "consentToken": "CBCU-2xxx2bd4-31a5-4e14-8abb-4245b3f48f4a",
  "consents": [
    {
      "id": "12853700402",
      "status": "APPROVED",
      "name": "insights",
      "details": {},
      "expiryDate": "2025-11-11T11:42:04.596Z"
    }
  ]
}
```

If the `consentToken` does not exist, the API returns a `404 Not Found` response.

## Delete All Consents {#delete-all-consents}

To revoke all consents for a user, select **Delete All Consents** on the **Consents** info page. The reference app calls `DELETE /consents/{consentToken}` and removes every consent for that user.

### Implementation {#implementation-1}

* Java
* Python

```java
// ConsentsController.java

  @DeleteMapping("/deleteConsents")
  public ResponseEntity<Void> deleteConsents(@RequestParam String reference) {
    try {
      apiService.getApiClient().deleteConsents(reference);
      return ResponseEntity.ok().build();
    } catch (Exception e) {
      log.error(e.getMessage());
    }
    return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
  }
```

```python
@app.route("/deleteConsents", methods=['DELETE'])
def delete_consents():
    reference = request.args.get('reference')
    resp = api_delete_consents(reference)
    return resp
```

### Response {#response-1}

A successful delete returns `200 OK` with an empty response body. A subsequent `GET /consents/{consentToken}` returns `404 Not Found`, confirming the consents have been removed.

## Delete a Specific Consent {#delete-a-specific-consent}

To revoke a single consent without affecting others for the same user, first retrieve the consent list by selecting **Get User Consents** . Each consent in the list displays a **Delete** link. Select the link next to the consent you want to revoke. The reference app calls `DELETE /consents/{consentToken}/consents/{consentId}` to remove only that consent.

### Implementation {#implementation-2}

* Java
* Python

```java
// ConsentsController.java

  @DeleteMapping("/deleteConsent")
  public ResponseEntity<Void> deleteConsent(@RequestParam String reference,
      @RequestParam String consentId) {
    try {
      apiService.getApiClient().deleteConsent(reference, consentId);
      return ResponseEntity.ok().build();
    } catch (Exception e) {
      log.error(e.getMessage());
    }
    return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
  }
```

```python
@app.route("/deleteConsent", methods=['DELETE'])
def delete_consent():
    reference = request.args.get('reference')
    consent_id = request.args.get('consentId')
    resp = api_delete_consent(reference, consent_id)
    return resp
```

The `consent_id` is taken from the consent list returned by the Get Consents call.

## Next Steps {#next-steps}

* Review the [Testing](https://developer.mastercard.com/consent-management/documentation/testing/index.md) page for test cases covering Get Consents and Delete Consents scenarios.
* See the [API Reference](https://developer.mastercard.com/consent-management/documentation/api-reference/index.md) for full request and response details.
