Yandex Wiki API usage examples

In this cluster, you'll find examples of Python scripts that use the Yandex Wiki API to manage forms and responses.

In all examples, either the OAuth protocol or an IAM token is used for authentication. To learn how to get a token, see API access.

1. Create a page and add content

Below, you'll find an example of a script you can use to do the following:

  • Create a new page.
  • Edit page content.
  • Retrieve the attributes of a page using its supertag (path).

This example assumes that an OAuth token is used for authentication (see Get access to the API using the OAuth protocol).

Text of the api_example_1.py script
import os
import requests
import sys

WIKI_PUBLIC_API = 'https://api.wiki.yandex.net/v1'
WIKI_TOKEN = os.environ.get('WIKI_TOKEN')


def create_wiki_page(
    *, supertag: str,
    org_id: str,
    title: str,
    content: str,
) -> int:
    """
    Create a new page

    Parameters:
    - supertag: supertag (slug) of the page being created
    - org_id: organization code
    - title: page title
    - content: page text
    """
    url = f'{WIKI_PUBLIC_API}/pages'
    headers = {
        'Authorization': f'OAuth {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    body = {
        'page_type': 'wysiwyg',
        'slug': supertag,
        'title': title,
        'content': content,
    }
    response = requests.post(url, json=body, headers=headers)
    if response.status_code != 200:
        return None

    res = response.json()
    return res.get('id')


def change_wiki_page(
    *, page_id: int,
    org_id: str,
    title: str = None,
    content: str = None,
) -> bool:
    """
    Edit an existing page

    Parameters:
    - page_id: page code
    - org_id: organization code
    - title: page title
    - content: page text
    """
    url = f'{WIKI_PUBLIC_API}/pages/{page_id}'
    headers = {
        'Authorization': f'OAuth {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    body = {}
    if title:
        body['title'] = title
    if content:
        body['content'] = content
    response = requests.post(url, json=body, headers=headers)
    return response.status_code == 200


def append_wiki_page_content(
    *, page_id: int,
    org_id: str,
    content: str,
    location: str = None,
) -> bool:
    """
    Add content to an existing page

    Parameters:
    - page_id: page code
    - org_id: organization code
    - content: text to insert
    - location: position to insert text:
      it's possible to insert it at the top of the page using `top`, at the bottom of the page using `bottom`,
      or under the anchor, for example, `#fragment`
    """
    url = f'{WIKI_PUBLIC_API}/pages/{page_id}/append-content'
    headers = {
        'Authorization': f'OAuth {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    body = {
        'content': content,
    }
    if location in ('top', 'bottom'):
        body['body'] = {'location': location}
    elif isinstance(location, str) and location.startswith('#'):
        body['anchor'] = {'name': location}
    else:
        body['body'] = {'location': 'bottom'}
    response = requests.post(url, json=body, headers=headers)
    return response.status_code == 200


def get_wiki_page_attributes(
    *, supertag: str,
    org_id: str,
) -> int:
    """
    Get the attributes of an existing page using its supertag

    Parameters:
    - supertag: supertag (slug) of an existing page
    - org_id: organization code
    """
    url = f'{WIKI_PUBLIC_API}/pages'
    params = {
        'slug': supertag,
    }
    headers = {
        'Authorization': f'OAuth {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    response = requests.get(url, params=params, headers=headers)
    if response.status_code == 200:
        return response.json()


def main():
    if len(sys.argv) < 2:
        sys.exit(1)
    org_id = sys.argv[1]

    supertag = 'users/test/pageone'

    # let's create a new page
    new_page_id = create_wiki_page(
        supertag=supertag,
        title='Page 1',
        content=(
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
            'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n'
        ),
        org_id=org_id,
    )
    if new_page_id:
        print(f'created page with code {new_page_id}')

    # let's rewrite the page content (important: using this method, you replace all content on the page)
    is_changed = change_wiki_page(
        page_id=new_page_id,
        org_id=org_id,
        title='Page number one',
        content=(
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
            'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n'
            'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris '
            'nisi ut aliquip ex ea commodo consequat.\n'
            'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum '
            'dolore eu fugiat nulla pariatur.\n'
            'Excepteur sint occaecat cupidatat non proident, '
            'sunt in culpa qui officia deserunt mollit anim id est laborum.\n'
        ),
    )
    if is_changed:
        print('page content rewritten')


    # let's retrieve page attributes using its supertag
    page_attributes = get_wiki_page_attributes(
        supertag=supertag,
        org_id=org_id,
    )
    if not page_attributes:
        print('wiki page not found')
        sys.exit(1)
    page_id = page_attributes.get('id')
    print(f'found page with code {page_id}')


if __name__ == '__main__':
    main()

Here's an example of how to launch a script (an organization code is used as an argument):

$ WIKI_TOKEN=$(cat .wiki-token) python api_example_1.py 'd3509bd2-b226-421a-94f1-1bf5b0e5fbf3'
created page with code 464211
page content rewritten
found page with code 464211

2. Create a dynamic table, add columns and rows

Below, you'll find an example of a script you can use to do the following:

  • Add a new dynamic table to an existing page.
  • Add columns and rows to a table.
  • Edit cells in a row.
  • Publish a table on a page.

This example assumes that an IAM token is used for authentication (see Access the API with an IAM token).

Text of the api_example_2.py script
import os
import requests
import sys

WIKI_PUBLIC_API = 'https://api.wiki.yandex.net/v1'
WIKI_TOKEN = os.environ.get('WIKI_TOKEN')

def get_wiki_page_attributes(
    *, supertag: str,
    org_id: str,
) -> int:
    """
    Get the attributes of an existing page using its supertag

    Parameters:
    - supertag: supertag (slug) of an existing page
    - org_id: organization code
    """
    url = f'{WIKI_PUBLIC_API}/pages'
    params = {
        'slug': supertag,
    }
    headers = {
        'Authorization': f'Bearer {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    response = requests.get(url, params=params, headers=headers)
    if response.status_code == 200:
        return response.json()


def create_wiki_grid(
    *, page_id: int,
    title: str,
    org_id: str,
) -> int:
    """
    Create a new table

    Parameters:
    - page_id: page code
    - org_id: organization code
    - title: table header

    Important! After creating a table, it's only available through the resource view interface,
    so you need to add this table to a page.
    """
    url = f'{WIKI_PUBLIC_API}/grids'
    body = {
        'page': {'id': page_id},
        'title': title,
    }
    headers = {
        'Authorization': f'Bearer {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    response = requests.post(url, json=body, headers=headers)
    if response.status_code == 200:
        res = response.json()
        return res.get('id')


def insert_grid_columns(
    *, grid_id: str,
    org_id: str,
    columns: list[dict],
) -> bool:
    """
    Add columns to a table

    Parameters:
    - grid_id: table code
    - org_id: organization code
    - columns: list of columns to add
    """
    url = f'{WIKI_PUBLIC_API}/grids/{grid_id}/columns'
    body = {
        'columns': columns,
    }
    headers = {
        'Authorization': f'Bearer {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    response = requests.post(url, json=body, headers=headers)
    return response.status_code == 200


def insert_grid_rows(
    *, grid_id: str,
    org_id: str,
    rows: list[dict],
) -> bool:
    """
    Add rows to a table

    Parameters:
    - grid_id: table code
    - org_id: organization code
    - rows: list of rows to add
    """
    url = f'{WIKI_PUBLIC_API}/grids/{grid_id}/rows'
    body = {
        'rows': rows,
    }
    headers = {
        'Authorization': f'Bearer {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    response = requests.post(url, json=body, headers=headers)
    return response.status_code == 200


def change_grid_cells(
    *, grid_id: str,
    org_id: str,
    cells: list[dict],
) -> bool:
    """
    Edit cells in a table

    Parameters:
    - grid_id: table code
    - org_id: organization code
    - cells: list of cell to edit
    """
    url = f'{WIKI_PUBLIC_API}/grids/{grid_id}/cells'
    body = {
        'cells': cells,
    }
    headers = {
        'Authorization': f'Bearer {WIKI_TOKEN}',
        'X-Org-Id': org_id,
    }
    response = requests.post(url, json=body, headers=headers)
    return response.status_code == 200


def main():
    if len(sys.argv) < 2:
        sys.exit(1)
    org_id = sys.argv[1]

    supertag = 'users/test/pageone'

    # let's retrieve page attributes using its supertag
    page_attributes = get_wiki_page_attributes(
        supertag=supertag,
        org_id=org_id,
    )
    if not page_attributes:
        print('wiki page not found')
        sys.exit(1)
    page_id = page_attributes.get('id')
    print(f'found page with code {page_id}')

    # let's create a new table
    grid_id = create_wiki_grid(
        page_id=page_id,
        title='New table',
        org_id=org_id,
    )
    if grid_id:
        print(f'created table with code {grid_id}')

    # let's add columns to the new table (columns can be of different types)
    is_changed = insert_grid_columns(
        grid_id=grid_id,
        org_id=org_id,
        columns=[
            {
                'slug': 'id',
                'title': 'ID',
                'type': 'number',
                'required': True,
            },
            {
                'slug': 'name',
                'title': 'Name',
                'type': 'string',
                'required': False,
            },
        ],
    )
    if is_changed:
        print('new columns added to table')

    # let's add rows to the new table
    is_changed = insert_grid_rows(
        grid_id=grid_id,
        org_id=org_id,
        rows=[
            {'id': 1, 'name': 'One'},
            {'id': 2, 'name': 'Two'},
            {'id': 3, 'name': 'Three'},
            {'id': 4, 'name': 'Four'},
            {'id': 5, 'name': 'Five'},
        ],
    )
    if is_changed:
        print('new rows added to table')

    # let's edit cells in the second row of the table
    is_changed = change_grid_cells(
        grid_id=grid_id,
        org_id=org_id,
        cells=[
            {'row_id': 2, 'column_slug': 'id', 'value': 22},
            {'row_id': 2, 'column_slug': 'name', 'value': 'Twenty-two'},
        ],
    )
    if is_changed:
        print('edited second row in table')

    # let's place the new table at the bottom of the page
    is_changed = append_wiki_page_content(
        page_id=page_id,
        org_id=org_id,
        content=f'\n{{% wgrid id="{grid_id}" %}}',
    )
    if is_changed:
        print('table created is added to page bottom')


if __name__ == '__main__':
    main()
$ WIKI_TOKEN=$(cat .wiki-token) python api_example_2.py 'd3509bd2-b226-421a-94f1-1bf5b0e5fbf3'
found page with code 464211
created table with code 252a78f2-90c2-43ba-a608-df7da23f1fd2
new columns added to table
new rows added to table
edited second row in table
table created is added to page bottom
Previous