[Yandex Cloud documentation](../../index.md) > [Yandex Cloud Functions](../index.md) > [Tutorials](index.md) > Serverless-based backend > Connecting to a YDB database from a Python function

# Connecting to a Yandex Managed Service for YDB database from a Python function in Cloud Functions

Create a [function](../concepts/function.md) with a [Python](https://python.org/) application that runs a simple query against a [Yandex Managed Service for YDB](../../ydb/index.md) database.

Use a metadata service to authorize your function with an associated [service account](../../iam/concepts/users/service-accounts.md) in YDB.

The application creates a YDB database connection driver, a session, and a transaction, and runs a query using the `ydb` library. This library is installed as a [dependency](../lang/python/dependencies.md) when creating a function version. The database connection parameters are provided to the application using environment variables.

To create a function and connect to the database:
1. [Get your cloud ready](#before-begin).
1. [Create a service account](#create-sa).
1. [Create a YDB database](#create-database).
1. [Create a function](#create-function).
1. [Test the function](#test-function).

If you no longer need the resources you created, [delete them](#clear-out).

## Get your cloud ready {#before-begin}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).

### Required paid resources {#paid-resources}

The infrastructure support cost for this tutorial includes:
* Fee for using the function (see [Yandex Cloud Functions pricing](../pricing.md)).
* Fee for running queries against the database (see [Managed Service for YDB pricing](../../ydb/pricing/serverless.md)).

## Create a service account {#create-sa}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) where you want to create your service account.
  1. Navigate to **Identity and Access Management**.
  1. Click **Create service account**.
  1. Enter a name for the service account, e.g., `sa-function`. The naming requirements are as follows:

     * Length: between 3 and 63 characters.
     * It can only contain lowercase Latin letters, numbers, and hyphens.
     * It must start with a letter and cannot end with a hyphen.

  1. Click **Add role** and select `editor`.
  1. Click **Create**.

{% endlist %}

## Create a YDB database {#create-database}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create a database.
  1. Navigate to **Managed Service for&nbsp;YDB**.
  1. Click **Create a database**.
  1. Name the database. The naming requirements are as follows:

     * Length: between 3 and 63 characters.
     * It can only contain lowercase Latin letters, numbers, and hyphens.
     * It must start with a letter and cannot end with a hyphen.

  1. Under **Database type**, select `Serverless`.
  1. Click **Create a database**.

     Wait for the database to start. While being created, the database will have the `Provisioning` status. Once it is ready for use, its status will change to `Running`.
  1. Click the database name.
  1. Under **Connection**, find the **Endpoint** field and save its value. You will need it at the next step.

{% endlist %}

## Create a function {#create-function}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the folder where you want to create a function.
  1. Navigate to **Cloud Functions**.
  1. Click **Create function**.
  1. Enter a name and description for the function. The naming requirements are as follows:

     * Length: between 3 and 63 characters.
     * It can only contain lowercase Latin letters, numbers, and hyphens.
     * It must start with a letter and cannot end with a hyphen.

  1. Click **Create**.
  1. Under **Editor**, select `Python` as the runtime, disable **Add files with code examples**, and click **Continue**.
  1. Under **Function code**, create a file named `index.py` and paste the following code into it:

     ```python
     import os
     import ydb
     import ydb.iam

     # Create driver in global space.
     driver = ydb.Driver(
       endpoint=os.getenv('YDB_ENDPOINT'),
       database=os.getenv('YDB_DATABASE'),
       credentials=ydb.iam.MetadataUrlCredentials(),
     )

     # Wait for the driver to become active for requests.

     driver.wait(fail_fast=True, timeout=5)

     # Create the session pool instance to manage YDB sessions.
     pool = ydb.SessionPool(driver)

     def execute_query(session):
       # Create the transaction and execute query.
       return session.transaction().execute(
         'select 1 as cnt;',
         commit_tx=True,
         settings=ydb.BaseRequestSettings().with_timeout(3).with_operation_timeout(2)
       )

     def handler(event, context):
       # Execute query with the retry_operation helper.
       result = pool.retry_operation_sync(execute_query)
       return {
         'statusCode': 200,
         'body': str(result[0].rows[0].cnt == 1),
       }
     ```

  1. Under **Function code**, create a file named `requirements.txt` and paste the following text into it:

     ```txt
     ydb
     ```

  1. Specify the entry point: `index.handler`.
  1. Select a service account, e.g., `sa-function`.
  1. Configure the environment variables:
     * `YDB_ENDPOINT`: Enter the first part of the previously saved **Endpoint** field value (preceding `/?database=`), e.g., `grpcs://ydb.serverless.yandexcloud.net:2135`.
     * `YDB_DATABASE`: Enter the second part of the previously saved **Endpoint** field value (following `/?database=`), e.g., `/ru-central1/r1gra875baom********/g5n22e7ejfr1********`.
  1. Click **Save changes**.

{% endlist %}

## Test the function {#test-function}

{% list tabs group=instructions %}

- Management console {#console}

  1. Navigate to the **Testing** tab.
  1. Click **Run test** and check out the test results.

     If your database is connected and successfully queried, the function status will change to `Completed` and its output will contain the following text:

     ```json
     {
       "statusCode": 200,
       "body": "True"
     }
     ```

{% endlist %}

## How to delete the resources you created {#clear-out}

To stop paying for the resources you created:
1. [Delete the database](../../ydb/operations/manage-databases.md#delete-db).
1. [Delete the function](../operations/function/function-delete.md).