{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "ef283f37-0ad4-48c7-bb92-8a09baaae6e5",
      "metadata": {},
      "source": [
        "---\n",
        "title: Retrieve and save job results\n",
        "description: How to use job_id to retrieve results, and how to save results to disk.\n",
        "---\n",
        "\n",
        "# Retrieve and save job results\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f4471d6b-dc12-486c-95de-22ac12e367d2",
      "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",
        "<Accordion>\n",
        "  <AccordionItem title=\"Package versions\">\n",
        "    The code on this page was developed using the following requirements.\n",
        "    We recommend using these versions or newer.\n",
        "\n",
        "    ```\n",
        "    qiskit-ibm-runtime~=0.45.1\n",
        "    ```\n",
        "  </AccordionItem>\n",
        "</Accordion>\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ec8277ad-1811-4318-8282-84d6d282bb17",
      "metadata": {},
      "source": [
        "Quantum workflows often take a while to complete and can run over many sessions. Restarting your Python kernel means you'll lose any results stored in memory. To avoid loss of data, you can save results to file and retrieve results of past jobs from IBM Quantum® so your next session can continue where you left off.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d32e82e4-331c-43ec-ac86-a657f29f1469",
      "metadata": {},
      "source": [
        "## Retrieve job results from IBM Quantum\n",
        "\n",
        "IBM Quantum automatically stores results from every job for you to retrieve at a later date. Use this feature to continue quantum programs across kernel restarts and review past results. You can get the ID of a job programmatically through its `job_id` method, or you can see all your submitted jobs and their IDs on the [Workloads page](/workloads).\n",
        "\n",
        "To find a job programmatically, use the [`QiskitRuntimeService.jobs`](/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#jobs) method. By default, this returns the most recently submitted jobs, but you can also filter jobs by backend name, creation date, and more. The following cell finds any jobs submitted in the last three months. The `created_after` argument must be a [`datetime.datetime`](https://docs.python.org/3.8/library/datetime.html#datetime.datetime) object.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "bd46b47b-e9ff-4da3-9ded-30dd3baee7c0",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[<RuntimeJobV2('d762oo5bjrds73ed2u80', 'estimator')>,\n",
              " <RuntimeJobV2('d762omnq1anc738d2cj0', 'sampler')>,\n",
              " <RuntimeJobV2('d762oma3qcgc73fse6dg', 'sampler')>]"
            ]
          },
          "execution_count": 1,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "import datetime\n",
        "from qiskit_ibm_runtime import QiskitRuntimeService\n",
        "\n",
        "three_months_ago = datetime.datetime.now() - datetime.timedelta(days=90)\n",
        "\n",
        "service = QiskitRuntimeService()\n",
        "jobs_in_last_three_months = service.jobs(created_after=three_months_ago)\n",
        "jobs_in_last_three_months[:3]  # show first three jobs"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "418755af-ddf1-4702-9c83-df23d29982f3",
      "metadata": {},
      "source": [
        "You can also select by backend, job state, session, and more. For more information, see [`QiskitRuntimeService.jobs`](/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#jobs) in the API documentation.\n",
        "\n",
        "Once you have the job ID, use the [`QiskitRuntimeService.job`](/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#job) method to retrieve it.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "bd1fc5a5-ad29-4805-91e5-fe70cdbc4540",
      "metadata": {
        "tags": [
          "ignore-warnings"
        ]
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "d762omnq1anc738d2cj0\n"
          ]
        }
      ],
      "source": [
        "# Get ID of most recent successful job for demonstration.\n",
        "# This will not work if you've never successfully run a job.\n",
        "successful_job = next(\n",
        "    j for j in service.jobs(limit=1000) if j.status() == \"DONE\"\n",
        ")\n",
        "job_id = successful_job.job_id()\n",
        "print(job_id)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "850780cc-4c91-4eec-9d46-2b2cbcd9157e",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(), num_shots=4096, num_bits=127>)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([DoubleSliceSpan(<start='2026-03-31 20:19:56', stop='2026-03-31 20:19:58', size=4096>)])}, 'version': 2})"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "retrieved_job = service.job(job_id)\n",
        "retrieved_job.result()"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f3bccdba-29c5-405b-96e2-65f4fe4ffadd",
      "metadata": {},
      "source": [
        "## Save results to disk\n",
        "\n",
        "You may also want to save results to disk. To do this, use Python's built-in JSON library with encoders from Qiskit Runtime.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "1892f8f7-ff0f-4ed2-bba9-a336c23315af",
      "metadata": {},
      "outputs": [],
      "source": [
        "import json\n",
        "from qiskit_ibm_runtime import RuntimeEncoder\n",
        "\n",
        "with open(\"result.json\", \"w\") as file:\n",
        "    json.dump(retrieved_job.result(), file, cls=RuntimeEncoder)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8fdddde9-2c05-481b-84c8-d3b7fcf70120",
      "metadata": {},
      "source": [
        "You can then load this array from disk in a separate kernel.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "71d963dd-3b66-4226-be7b-c69bc89af28e",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "PrimitiveResult([SamplerPubResult(data=DataBin(meas=BitArray(<shape=(), num_shots=4096, num_bits=127>)), metadata={'circuit_metadata': {}})], metadata={'execution': {'execution_spans': ExecutionSpans([DoubleSliceSpan(<start='2026-03-31 20:19:56', stop='2026-03-31 20:19:58', size=4096>)])}, 'version': 2})"
            ]
          },
          "execution_count": 5,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from qiskit_ibm_runtime import RuntimeDecoder\n",
        "\n",
        "with open(\"result.json\", \"r\") as file:\n",
        "    result = json.load(file, cls=RuntimeDecoder)\n",
        "\n",
        "result"
      ]
    },
    {
      "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
}