{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "38b90986-2529-4974-9dbd-931f3089b7fa",
      "metadata": {},
      "source": [
        "---\n",
        "title: Execution modes using REST API\n",
        "description: How to run a quantum computing job in an IBM Quantum Compute Service session.\n",
        "---\n",
        "\n",
        "# Execution modes using REST API\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d501206a-c250-4df7-befc-317678659d32",
      "metadata": {
        "tags": [
          "version-info"
        ]
      },
      "source": [
        "{/*\n",
        "  DO NOT EDIT THIS CELL!!!\n",
        "  This cell's content is generated automatically by a script. Anything you add\n",
        "  here will be removed next time the notebook is run. To add new content, create\n",
        "  a new cell before or after this one.\n",
        "  */}\n",
        "\n",
        "<details>\n",
        "  <summary><b>Package versions</b></summary>\n",
        "\n",
        "  The code on this page was developed using the following requirements.\n",
        "  We recommend using these versions or newer.\n",
        "\n",
        "  ```\n",
        "  qiskit[all]~=2.3.0\n",
        "  ```\n",
        "</details>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2153584e-5711-4168-a4a5-0b94d02dd3e7",
      "metadata": {},
      "source": [
        "You can run your IBM Quantum primitive workloads using REST APIs in one of three execution modes, depending on your needs: job, session, and batch. This topic explains these modes.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  This documentation utilizes the Python `requests` module to demonstrate the IBM Quantum Compute Service REST API. However, this workflow can be executed using any language or framework that supports working with REST APIs. Refer to the [API reference documentation](/docs/api/qiskit-runtime-rest) for details.\n",
        "</Admonition>\n",
        "\n",
        "## Job mode with REST API\n",
        "\n",
        "In job mode, a single primitive request of Estimator or Sampler is made without a context manager. See how to run a quantum circuit using [Estimator](/docs/guides/estimator-rest-api) and [Sampler](/docs/guides/sampler-rest-api) for some examples.\n",
        "\n",
        "## Session mode with REST API\n",
        "\n",
        "A session is a feature that lets you efficiently run multi-job iterative workloads on quantum computers. Using sessions helps avoid delays caused by queuing each job separately, which can be particularly useful for iterative tasks that require frequent communication between classical and quantum resources. More details about Sessions can be found in the [documentation](/docs/guides/execution-modes).\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  Open Plan users cannot submit session jobs.\n",
        "</Admonition>\n",
        "\n",
        "### Start a session\n",
        "\n",
        "Begin by creating a session and obtaining a session ID.\n",
        "\n",
        "```python\n",
        "import json\n",
        "import requests\n",
        "\n",
        "sessionsUrl = \"https://quantum.cloud.ibm.com/api/v1/sessions\"\n",
        "auth_id = \"Bearer <YOUR_BEARER_TOKEN>\"\n",
        "backend = \"<BACKEND_NAME>\"\n",
        "crn = \"<SERVICE-CRN>\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Content-Type\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn\n",
        "}\n",
        "\n",
        "payload = json.dumps({\n",
        "  \"backend\": backend,\n",
        "  \"mode\": 'dedicated',\n",
        "})\n",
        "\n",
        "response = requests.request(\"POST\", sessionsUrl, data=payload,  headers=headersList)\n",
        "\n",
        "sessionId = response.json()['id']\n",
        "\n",
        "print(response.json())\n",
        "```\n",
        "\n",
        "Output\n",
        "\n",
        "```text\n",
        "{'id': 'crw9s7cdbt40008jxesg'}\n",
        "```\n",
        "\n",
        "### Close a session\n",
        "\n",
        "It is good practice to close a `Session` when all jobs are done. This will reduce wait time for subsequent users.\n",
        "\n",
        "```python\n",
        "closureURL=\"https://quantum.cloud.ibm.com/api/v1/sessions/\"+sessionId+\"/close\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn\n",
        "}\n",
        "\n",
        "closure_response = requests.request(\n",
        "    \"DELETE\",\n",
        "    closureURL,\n",
        "    headers=headersList\n",
        "    )\n",
        "\n",
        "print(\"Session closure response ok?:\",closure_response.ok,closure_response.text)\n",
        "```\n",
        "\n",
        "Output\n",
        "\n",
        "```text\n",
        "Session closure response ok?: True\n",
        "```\n",
        "\n",
        "## Batch mode with REST API\n",
        "\n",
        "Alternatively, you can submit a batch job by specifying the `mode` in the request payload. Batch mode can help shorten processing time if all jobs can be provided at the outset. Learn about batch mode in the [introduction to execution modes](/docs/guides/execution-modes#batch-mode) guide.\n",
        "\n",
        "```python\n",
        "import json\n",
        "import requests\n",
        "\n",
        "sessionsUrl = \"https://quantum.cloud.ibm.com/api/v1/sessions\"\n",
        "\n",
        "headersList = {\n",
        "  \"Accept\": \"application/json\",\n",
        "  \"Authorization\": auth_id,\n",
        "  \"Service-CRN\": crn,\n",
        "  'Content-Type': 'application/json'\n",
        "}\n",
        "\n",
        "payload = json.dumps({\n",
        "  \"backend\": backend,\n",
        "  \"instance\": \"hub1/group1/project1\",\n",
        "  \"mode\": \"batch\"\n",
        "})\n",
        "\n",
        "response = requests.request(\"POST\", sessionsUrl, data=payload,  headers=headersList)\n",
        "\n",
        "sessionId = response.json()['id']\n",
        "```\n",
        "\n",
        "## Examples of jobs submitted in a session\n",
        "\n",
        "Once a session is set up, one or more Sampler or Estimator jobs can be submitted to the same session by specifying the session ID.\n",
        "\n",
        "<Admonition type=\"note\">\n",
        "  The `<parameter values>` in a `PUB` can either be a single parameter or a list of parameters. It also supports `numpy` broadcasting.\n",
        "</Admonition>\n",
        "\n",
        "### Estimator jobs in session mode\n",
        "\n",
        "<Tabs>\n",
        "  <TabItem value=\"1 circuit, 4 observables\" label=\"1 circuit, 4 observables\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'estimator',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [obs1, obs2, obs3, obs4]]], #primitive unified blocs (PUBs) containing one circuit each.\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"1 circuit, 4 observables, 2 parameter sets\" label=\"1 circuit, 4 observables, 2 parameter sets\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'estimator',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [[obs1], [obs2], [obs3], [obs4]], [[vals1], [vals2]]]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"2 circuits, 2 observables\" label=\"2 circuits, 2 observables\">\n",
        "    ```python\n",
        "      job_input = {\n",
        "      'program_id': 'estimator',\n",
        "      \"backend\": backend,\n",
        "      \"session_id\": sessionId, # This specifies the previously created Session\n",
        "      \"params\": {\n",
        "          \"pubs\": [[resulting_qasm, obs1],[resulting_qasm, obs2]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "          \"options\":{\n",
        "                  \"transpilation\":{\"optimization_level\": 1},\n",
        "                  \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                  # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                      },\n",
        "      }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "</Tabs>\n",
        "\n",
        "### Sampler jobs in session mode\n",
        "\n",
        "<Tabs>\n",
        "  <TabItem value=\"1 circuit, no parameters\" label=\"1 circuit, no parameters\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'sampler',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"1 circuit, 3 parameter sets\" label=\"1 circuit, 3 parameter sets\">\n",
        "    ```python\n",
        "    job_input = {\n",
        "    'program_id': 'sampler',\n",
        "    \"backend\": backend,\n",
        "    \"session_id\": sessionId, # This specifies the previously created Session\n",
        "    \"params\": {\n",
        "        \"pubs\": [[resulting_qasm, [vals1, vals2, vals3]]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "        \"options\":{\n",
        "                \"transpilation\":{\"optimization_level\": 1},\n",
        "                \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                    },\n",
        "    }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "\n",
        "  <TabItem value=\"2 circuits, 1 parameter set\" label=\"2 circuits, 1 parameter set\">\n",
        "    ```python\n",
        "      job_input = {\n",
        "      'program_id': 'sampler',\n",
        "      \"backend\": backend,\n",
        "      \"session_id\": sessionId, # This specifies the previously created Session\n",
        "      \"params\": {\n",
        "          \"pubs\": [[resulting_qasm, [val1]],[resulting_qasm,None,100]], #primitive unified blocs (PUBs) containing one circuit each\n",
        "          \"options\":{\n",
        "                  \"transpilation\":{\"optimization_level\": 1},\n",
        "                  \"twirling\": {\"enable_gates\": True,\"enable_measure\": True},\n",
        "                  # \"dynamical_decoupling\": {\"enable\": True, \"sequence_type\": \"XpXm\"},   #(optional)\n",
        "                      },\n",
        "      }\n",
        "    }\n",
        "    ```\n",
        "  </TabItem>\n",
        "</Tabs>\n",
        "\n",
        "## Next steps\n",
        "\n",
        "<Admonition type=\"tip\" title=\"Recommendations\">\n",
        "  * Review detailed [Sampler](/docs/guides/sampler-rest-api) primitives examples using REST API.\n",
        "  * Review detailed [Estimator](/docs/guides/estimator-rest-api) primitives examples using REST API.\n",
        "  * Practice with primitives by working through the [Cost function lesson](/learning/courses/variational-algorithm-design/cost-functions) in IBM Quantum® Learning.\n",
        "  * Learn how to transpile locally in the [Transpile](/docs/guides/transpile) section.\n",
        "</Admonition>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}