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

The source code for the tutorial is available under [Reference App](https://developer.mastercard.com/consent-management/documentation/reference-app/index.md). Run the tutorial as follows:
* Java
* Python

```java
mvn spring-boot:run
```

```bash
FLASK_APP=main python3 -m flask run
```

When the tutorial app starts, it serves a webpage at `localhost:8081`. Navigate to 'User Consent Management API' and complete the form with the user details. Click 'Create Consent' to call the `/create-user-consent` endpoint.

<br />

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

* Java
* Python

```java
// ConsentsController.java

  /**
   * Call User Consent Management API to create the user consent token.
   *
   * @param userDetails
   * @param model
   * @param email
   * @param phone
   * @return String
   */
  @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():
    """ handle create user consent form """

    if request.method == 'POST':

        identities = []
        
        # Add email identity if provided
        if request.form.get("email"):
            identities.append({
                "type": "EMAIL",
                "value": request.form["email"],
                "verified": False
            })
        
        # Add phone identity if provided
        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')
```

After the user fills in the form fields (`fullName`, `postalCode`, `email`, and/or `phone`), these values are mapped to the corresponding fields in the `userDetails` object for the `/consents` API request. The `postalCode` is required, while other fields are optional and included as identities if provided. Below is the sample request format.
* Json
* Json

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

```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 API response returns a `consentToken` which serves as a unique identifier for the user. Store this token securely as it is required for:

* **Managing consents**: Call the manage consents APIs to retrieve or revoke user consents.
* **Updating user details** : Include the `consentToken` in the `userDetails` object when calling the consents API. The system will recognize the existing user and update their information accordingly

Once the consent is successfully created, the UI redirects to the `consents-info` page, displaying the `consentToken` from the response.

## Get Consents {#get-consents}

* Java
* Python

```java
// ConsentsController.java
   /**
   * Call Get Consents API to retrieve user consents.
   *
   * @param reference(consentToken)
   * @return consents
   */
  @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():
    """ get list of consents """
    reference = request.args.get('reference')

    resp = api_get_consents(reference)
    return resp
```

Upon a successful response from the `getConsents` API, you will receive a list of all consents associated with the user. These consents are displayed on the `consents-info` page, where you can view their details and revoke them as needed.

## Revoke Consents {#revoke-consents}

* Java
* Python

```java
// ConsentsController.java
   /**
   * Call Delete Consent API with consentId to revoke specific user consent.
   *
   * @param reference(consentToken)
   * @param consentId(consentId)
   * @return consents
   */
  @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);
  }

   /**
   * Call Delete Consent API to revoke all the consents.
   *
   * @param reference(consentToken)
   * @return consents
   */
  @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("/deleteConsent", methods=['DELETE'])
def delete_consent():
    """ delete single consent by card ref and consent id """
    reference = request.args.get('reference')
    consent_id = request.args.get('consentId')

    resp = api_delete_consent(reference, consent_id)
    return resp


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

