Skip to main content

aempsconn

Español · Migration guide from 1.1.1

aempsconn is a typed Python SDK for the CIMA REST API of the Spanish Agency of Medicines and Medical Devices (AEMPS). It sends the HTTP requests, validates the parameters, follows the pagination and returns pydantic models, so you work with Python objects instead of raw JSON.

The SDK follows the official CIMA REST API v1.23 document. Parameter and field names are the Spanish names used by CIMA, so the official document and the SDK read the same. The project is not affiliated with AEMPS.

Contents: requirements · installation · quick start · basic usage of every resource · getting all the data · reference · configuration · exceptions · API coverage · CIMA data and packaging regulation · security · migrating from 1.1.1 · development · contributing · license · disclaimer

Requirements

  • Python 3.11 or later. The CI tests Python 3.11, 3.12, 3.13, 3.14 and 3.15. Python 3.10 and older are not supported.
  • Network access to https://cima.aemps.es.
  • Runtime dependencies: pydantic 2, requests 2 and urllib3 2 (and tzdata on Windows, for the Europe/Madrid time zone).

Installation

pip install aempsconn

Quick start

from aempsconn import AempsConn

with AempsConn() as client:
    for med in client.medicamentos.get(nombre="metformina", comerc=True):
        print(med.nregistro, med.nombre)

AempsConn() needs no configuration: it uses the official base URL, verifies TLS, applies timeouts and retries failed reads a bounded number of times. One client holds one connection pool and can be shared between threads. Close it when you are done, or use it in a with block as above.

Basic usage of every resource

Each recipe below is self-contained and can be pasted into a Python session. Every resource is an attribute of the client, and every argument is a keyword argument named as the CIMA parameter. The SDK is a library: it has no command-line interface.

Search medicines by name

from aempsconn import AempsConn

client = AempsConn()
for med in client.medicamentos.get(nombre="metformina"):
    print(med.nregistro, med.nombre, med.labtitular)

# CIMA accepts "*" as a wildcard in text parameters (observed, not documented).
for med in client.medicamentos.get(nombre="metfor*", comerc=True, receta=True):
    print(med.nombre)
client.close()

Search by national code or registration number

from aempsconn import AempsConn

client = AempsConn()
for med in client.medicamentos.get(cn="712729"):
    print(med.nregistro, med.nombre)

for med in client.medicamentos.get(nregistro="51347"):
    print(med.nregistro, med.nombre)
client.close()

Search by active ingredient, ATC code or other criteria

from aempsconn import AempsConn
from aempsconn.enums import Sust

client = AempsConn()
for med in client.medicamentos.get(practiv1="metformina", practiv2="sitagliptina"):
    print(med.nombre)

for med in client.medicamentos.get(atc="A10BA02", comerc=True):
    print(med.nombre)

for med in client.medicamentos.get(sust=Sust.BIOLOGICOS, biosimilar=True):
    print(med.nombre)
client.close()

Every search parameter of the official document is available; see resources and parameters.

Fetch one medicine

from aempsconn import AempsConn

client = AempsConn()
med = client.medicamento.get(nregistro="51347")  # or client.medicamento.get(cn="712729")
if med is not None:
    print(med.nombre, med.pactivos)
    for presentation in med.presentaciones or []:
        print(presentation.cn, presentation.nombre, presentation.comerc)
    for ingredient in med.principiosActivos or []:
        print(ingredient.nombre, ingredient.cantidad, ingredient.unidad)

print(client.medicamento.get(nregistro="00000"))  # None: CIMA has no such medicine
client.close()

Presentations

from aempsconn import AempsConn

client = AempsConn()
for presentation in client.presentaciones.get(nregistro="51347"):
    print(presentation.cn, presentation.nombre)

detail = client.presentacion.get(cn="712729")  # None when the code does not exist
if detail is not None:
    print(detail.nombre, detail.labtitular, detail.psum)
client.close()

Search the technical sheet text

Each criterion names a technical sheet section, a text and whether the section must contain it. Every criterion must match.

from aempsconn import AempsConn, CriterioFichaTecnica
from aempsconn.enums import Contiene

client = AempsConn()
criterios = [
    CriterioFichaTecnica("4.1", "acidez", Contiene.SI),
    CriterioFichaTecnica("4.1", "estómago", Contiene.NO),
]
for med in client.buscar_en_ficha_tecnica.get(criterios):
    print(med.nregistro, med.nombre)
client.close()

Supply problems

from aempsconn import AempsConn

client = AempsConn()
for problem in client.psuministro.get():  # every current supply problem
    print(problem.cn, problem.nombre, problem.fini, problem.activo)

for problem in client.psuministro.get(cn="718816"):  # the problems of one presentation
    print(problem.observ)
client.close()

Clinical descriptions (VMP and VMPP)

from aempsconn import AempsConn

client = AempsConn()
for description in client.vmpp.get(practiv1="metformina"):
    print(description.vmp, description.vmpDesc, description.vmppDesc)

# modoArbol=True returns each VMP with its VMPPs (observed shape, not documented).
for vmp in client.vmpp.get(practiv1="metformina", modoArbol=True):
    print(vmp.vmp, [pack.vmpp for pack in vmp.vmpps or []])
client.close()

Safety notes

from aempsconn import AempsConn

client = AempsConn()
for note in client.notas.get(nregistro="69223"):  # a list; empty when there are none
    print(note.fecha, note.referencia, note.asunto, note.url)
client.close()

Informational materials

from aempsconn import AempsConn

client = AempsConn()
material = client.materiales.get(nregistro="78632")  # None when the medicine has none
if material is not None:
    for document in material.listaDocsPaciente or []:
        print(document.nombre, document.url)
    for video in material.videos or []:
        print(video.url)
client.close()

Master lists

maestra is required. Each catalogue is a member of Maestra.

from aempsconn import AempsConn
from aempsconn.enums import Maestra

client = AempsConn()
for item in client.maestras.get(maestra=Maestra.PRINCIPIOS_ACTIVOS, nombre="metformina"):
    print(item.item_id, item.codigo, item.nombre)

for lab in client.maestras.get(maestra=Maestra.LABORATORIOS, nombre="cinfa"):
    print(lab.nombre)

# enuso=False also returns active ingredients that no medicine uses.
for item in client.maestras.get(maestra=Maestra.PRINCIPIOS_ACTIVOS, nombre="metformina", enuso=False):
    print(item.nombre)
client.close()

Segmented documents

The technical sheet (FICHA_TECNICA) and the leaflet (PROSPECTO) can be read section by section, as typed sections, HTML or plain text.

from aempsconn import AempsConn
from aempsconn.enums import FormatoContenido, TipoDocSegmentado

client = AempsConn()
for section in client.doc_segmentado.secciones(TipoDocSegmentado.FICHA_TECNICA, nregistro="51347"):
    print(section.seccion, section.titulo)

sections = client.doc_segmentado.contenido(TipoDocSegmentado.FICHA_TECNICA, nregistro="51347", seccion="4.1")
print(sections[0].contenido)  # HTML fragment inside a SeccionModel

text = client.doc_segmentado.contenido(
    TipoDocSegmentado.FICHA_TECNICA, nregistro="51347", seccion="4.1", formato=FormatoContenido.TEXT
)
html = client.doc_segmentado.contenido(
    TipoDocSegmentado.PROSPECTO, nregistro="51347", seccion="1", formato=FormatoContenido.HTML
)
print(text[:80], len(html))
client.close()

HTML technical sheets and leaflets

from aempsconn import AempsConn

client = AempsConn()
sheet = client.documentos.ficha_tecnica("51347")  # the complete document
indications = client.documentos.ficha_tecnica("51347", seccion="4.1")
leaflet = client.documentos.prospecto("51347", seccion="1")
print(len(sheet), len(indications), len(leaflet))
client.close()

The PDF documents and images that CIMA links to (docs[].url, docs[].url_html, fotos[].url, the material url fields) are exposed as URLs; the SDK does not download them.

Change log

from datetime import date

from aempsconn import AempsConn

client = AempsConn()
for change in client.registro_cambios.get(fecha=date(2026, 11, 20)):
    print(change.nregistro, change.fecha, change.tipoCambio, change.cambio)

# A dd/mm/yyyy string also works, and nregistro may be repeated.
for change in client.registro_cambios.get(fecha="20/11/2026", nregistro=["51347", "BE114572"]):
    print(change.nregistro, change.tipoCambio)
client.close()

Pagination

List operations return a PagedResult: a lazy iterator in CIMA order. Nothing is requested until you read it, page 1 tells the SDK how many pages exist, and no page past the end is requested. CIMA serves 200 results per page.

from itertools import islice

from aempsconn import AempsConn

client = AempsConn()
result = client.medicamentos.get(nombre="metformina")
print(result.total)  # requests page 1 only
first = result.first_page()  # the same page 1, already fetched
print(first.number, first.size, first.total, len(first.items))
for med in result:  # continues with page 2, 3, ... as needed
    print(med.nombre)

for page in client.medicamentos.get(nombre="metformina").pages():  # page by page
    print(page.number, len(page.items))

first_ten = list(islice(client.medicamentos.get(nombre="metformina"), 10))  # one request
page_two = list(client.medicamentos.get(nombre="metformina", pagina=2))  # exactly page 2
client.close()

# Prefetch: up to 4 pages in flight per result; the order does not change.
with AempsConn(max_workers=4) as prefetching:
    names = [med.nombre for med in prefetching.medicamentos.get(nombre="metformina")]
    result = prefetching.medicamentos.get(nombre="metformina")
    print(result)  # PagedResult(operation='GET medicamentos', pages='all', state='new'); sends nothing
    first_name = next(result).nombre  # page 1; the following pages start loading
    result.close()  # abandon the result early: pending page requests are cancelled

A result is read either item by item or page by page, not both, and it is not meant to be shared between threads. Its repr shows the operation, the pages requested, the state and, once page 1 is loaded, the total, without sending a request. close() abandons a result early, for example after the first items with max_workers > 1: the prefetched page requests are cancelled and the iteration stops.

If a page after the first fails, or any page is inconsistent, iteration raises PaginationError: you never get a partial list without an error. A failure on page 1, of the request or of its results, raises the original error instead, for example HTTPStatusError or ResponseValidationError. A failed result keeps raising the same error from next() and pages(); to retry, call get(...) again, which starts over from page 1.

Error handling

Invalid parameters are rejected before any request is sent. Every error the SDK raises derives from AempsConnError.

from aempsconn import (
    AempsConn,
    AempsConnError,
    CimaTimeoutError,
    HTTPStatusError,
    PaginationError,
    QueryValidationError,
)

client = AempsConn()
try:
    client.registro_cambios.get(fecha="2026-11-20")
except QueryValidationError as err:
    print(err.parameter, "->", err.accepted)  # fecha -> a date, a datetime or a dd/mm/yyyy string

try:
    medicines = list(client.medicamentos.get(nombre="metformina"))
except PaginationError as err:  # a later page failed: no partial list
    print("page", err.page, "failed:", err.__cause__)
except HTTPStatusError as err:  # CIMA answered with an error status after the retries
    print(err.status_code, err.endpoint, err.body_excerpt)
except CimaTimeoutError as err:
    print("timed out:", err)
except AempsConnError as err:  # any other SDK error
    print("CIMA request failed:", err)
client.close()

A lookup that finds nothing is not an error: medicamento.get, presentacion.get and materiales.get return None, notas.get returns an empty list and list operations yield nothing.

Filter objects (1.1.1 style)

The chainable filter objects of 1.1.1 still work and send the same requests as the keyword arguments. They cannot be combined with keyword arguments in the same call.

from aempsconn import AempsConn
from aempsconn.query import MedicamentosFilter, VmppFilter

client = AempsConn()
query = MedicamentosFilter().nombre.startswith("metfor").comercializado.equals(True)
for med in client.medicamentos.get(query):
    print(med.nombre)

tree = VmppFilter().pactivo1.equals("metformina").modo_arbol.equals(True)  # use the returned filter
for vmp in client.vmpp.get(tree):
    print(vmp.vmp)
client.close()

Getting all the data

There is no bulk download in CIMA or in the SDK: a copy of the data is built from the normal operations. The examples in this section download the whole catalogue, so read request cost and fair use before running them.

The full list of medicines

client.medicamentos.get() without parameters iterates every medicine in CIMA, authorised or not. At the time of writing (November 2026) that was 25,560 medicines: 20,572 authorised and 4,988 not authorised, and 16,141 of them marketed. At 200 per page that is about 128 requests. The list items carry the main fields (status, laboratory, flags, documents, photos); the detail of each medicine adds the active ingredients, excipients, ATC codes and presentations.

from aempsconn import AempsConn

with AempsConn() as client:
    medicines = client.medicamentos.get()
    print(medicines.total)  # check the size first: only page 1 is requested
    with open("medicamentos.jsonl", "w", encoding="utf-8") as out:
        for med in medicines:
            out.write(med.model_dump_json(by_alias=True) + "\n")

model_dump_json(by_alias=True) writes the CIMA field names, including any field CIMA returns that the models do not declare. Use client.medicamentos.get(autorizados=True) or comerc=True to download a subset.

The full detail of every medicine

The detail is one request per medicine (client.medicamento.get(nregistro=...)), that is about 25,560 more requests. The client is thread-safe, so a small thread pool can share it. This example uses 4 workers, works in batches so that an error stops it quickly, and resumes from the registration numbers already saved.

import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

from aempsconn import AempsConn

output = Path("medicamentos_detalle.jsonl")
done: set[str] = set()
if output.exists():
    with output.open(encoding="utf-8") as lines:
        done = {json.loads(line)["nregistro"] for line in lines}

with AempsConn() as client:
    pending = [med.nregistro for med in client.medicamentos.get() if med.nregistro not in done]

    def fetch_detail(nregistro: str) -> str | None:
        med = client.medicamento.get(nregistro=nregistro)
        return None if med is None else med.model_dump_json(by_alias=True)

    with ThreadPoolExecutor(max_workers=4) as pool, output.open("a", encoding="utf-8") as out:
        for start in range(0, len(pending), 100):
            for line in pool.map(fetch_detail, pending[start : start + 100]):
                if line is not None:
                    out.write(line + "\n")
            out.flush()

If the run stops (an error, a closed laptop), run it again: it skips the medicines already in the file.

Saving to SQLite

The standard library is enough to keep a local, queryable copy. This example stores each medicine of the list as a row, with the full JSON in one column, and updates the rows that already exist.

import sqlite3

from aempsconn import AempsConn

db = sqlite3.connect("cima.sqlite3")
try:
    with db, AempsConn() as client:  # one transaction: committed at the end, rolled back on error
        db.execute(
            "CREATE TABLE IF NOT EXISTS medicamentos ("
            "nregistro TEXT PRIMARY KEY, nombre TEXT NOT NULL, comerc INTEGER, data TEXT NOT NULL)"
        )
        db.executemany(
            "INSERT INTO medicamentos (nregistro, nombre, comerc, data) VALUES (?, ?, ?, ?) "
            "ON CONFLICT (nregistro) DO UPDATE SET "
            "nombre = excluded.nombre, comerc = excluded.comerc, data = excluded.data",
            (
                (med.nregistro, med.nombre, med.comerc, med.model_dump_json(by_alias=True))
                for med in client.medicamentos.get()
            ),
        )
    print(db.execute("SELECT COUNT(*) FROM medicamentos").fetchone()[0])
finally:
    db.close()

Incremental sync

After the first download, client.registro_cambios.get(fecha=last_sync) lists the medicines that are new, were withdrawn or were modified since a date. tipoCambio tells which (TipoCambio.NUEVO, BAJA or MODIFICADO) and cambio lists the changed areas (CambioRegistro: status, marketing, leaflet, technical sheet, supply problems, safety notes, materials and others). Fetch the detail of each changed medicine again and store the date the sync started; repeating a day is harmless.

from datetime import date
from pathlib import Path

from aempsconn import AempsConn

state = Path("last_sync.txt")
last_sync = date.fromisoformat(state.read_text()) if state.exists() else date(2026, 11, 1)
started = date.today()

with AempsConn() as client:
    changed: set[str] = set()
    for change in client.registro_cambios.get(fecha=last_sync):
        print(change.nregistro, change.tipoCambio, change.cambio)
        changed.add(change.nregistro)
    for nregistro in sorted(changed):
        med = client.medicamento.get(nregistro=nregistro)
        if med is None:
            print("no longer in CIMA:", nregistro)  # delete it from your copy
        else:
            print("store:", med.nregistro, med.nombre)  # insert or update it in your copy

state.write_text(started.isoformat())

Request cost and fair use

Task Requests (November 2026)
Full list, client.medicamentos.get() about 128 (25,560 medicines, 200 per page)
Full detail, client.medicamento.get(nregistro=...) about 25,560 (one per medicine)
Incremental sync one per 200 changes, plus one detail per changed medicine
Safety notes, materials, segmented documents, HTML documents one per medicine and operation
Supply problems one per 200 problems for the whole list, or one per presentation

Safety notes, informational materials, supply problems and segmented documents are not part of the medicine detail: each one is a separate call. The list flags tell you which medicines have them, so you can skip the rest:

from aempsconn import AempsConn

with AempsConn() as client:
    medicines = list(client.medicamentos.get())
    with_notes = [med.nregistro for med in medicines if med.notas]
    with_materials = [med.nregistro for med in medicines if med.materialesInf]
    with_supply_problems = [med.nregistro for med in medicines if med.psum]
    print(len(with_notes), len(with_materials), len(with_supply_problems))

CIMA publishes no rate limits. It is a public service, so please be moderate:

  • keep concurrency low (the examples use 4 workers; the SDK prefetches at most 4 pages per result);
  • run full downloads off-peak, and prefer the incremental sync to downloading everything again;
  • make long jobs resumable, as in the detail example, so that a failure does not repeat the work done;
  • keep the default retries: they back off with jitter and honour Retry-After.

Reference

Resources and parameters

Client attribute CIMA operation Call Returns
medicamentos GET medicamentos get(nombre, laboratorio, practiv1, practiv2, idpractiv1, idpractiv2, cn, atc, nregistro, npactiv, triangulo, huerfano, biosimilar, sust, vmp, comerc, autorizados, receta, estupefaciente, psicotropo, estuopsico, pagina) PagedResult[MedicamentosModel]
medicamento GET medicamento get(nregistro=...) or get(cn=...), exactly one MedicamentoModel | None
buscar_en_ficha_tecnica POST buscarEnFichaTecnica get(criterios, pagina=None) PagedResult[MedicamentosModel]
presentaciones GET presentaciones get(cn, nregistro, vmp, vmpp, idpractiv1, comerc, estupefaciente, psicotropo, estuopsico, pagina) PagedResult[PresentacionesModel]
presentacion GET presentacion/{cn} get(cn=...) PresentacionDetalleModel | None
psuministro GET psuministro, GET psuministro/{cn} get(cn=None, pagina=None) PagedResult[ProblemaSuministroModel]
vmpp GET vmpp get(practiv1, idpractiv1, dosis, forma, atc, nombre, modoArbol, pagina) PagedResult[DescripcionClinicaModel]; PagedResult[VmpArbolModel] with modoArbol=True
notas GET notas/{nregistro} get(nregistro=...) list[NotaModel]
materiales GET materiales/{nregistro} get(nregistro=...) MaterialModel | None
maestras GET maestras get(maestra, nombre, id, codigo, estupefaciente, psicotropo, estuopsico, enuso, pagina) PagedResult[ItemModel]
registro_cambios GET registroCambios get(fecha, nregistro, pagina) PagedResult[RegistroCambiosModel]
doc_segmentado GET docSegmentado/secciones/{tipoDoc}, GET docSegmentado/contenido/{tipoDoc} secciones(tipo_doc, nregistro=...), contenido(tipo_doc, nregistro=..., seccion=None, formato=FormatoContenido.JSON) list[SeccionModel]; str with HTML or TEXT
documentos GET dochtml/ft/..., GET dochtml/p/... ficha_tecnica(nregistro, seccion=None), prospecto(nregistro, seccion=None) str (HTML)

How the arguments are validated and sent:

  • Every argument is optional unless stated, keyword-only and named as in CIMA. Invalid values raise QueryValidationError, naming the parameter and the accepted values, before anything is sent. This matters because CIMA ignores values it does not understand and then returns unfiltered results.
  • maestra (in maestras) and fecha (in registro_cambios) are required.
  • Flags (triangulo, huerfano, biosimilar, comerc, autorizados, receta) take True or False, sent as 1 or 0.
  • estupefaciente, psicotropo, estuopsico and modoArbol are documented with the value 1 only: True sends 1 and False sends nothing. enuso is documented with 0 only: False sends enuso=0 and True sends nothing.
  • Text is sent verbatim. Identifiers (idpractiv1, idpractiv2, vmp, vmpp, id) are numbers of at most 18 digits, as int or str. npactiv and pagina are integers of at least 1, also of at most 18 digits.
  • sust takes a Sust member or its code (1 to 5); maestra a Maestra member or its code.
  • fecha takes a date, a datetime or a dd/mm/yyyy string, and is sent as dd/mm/yyyy. nregistro in registro_cambios takes one value or a list, and each value is sent as its own nregistro parameter.
  • In maestras, the id argument is sent with the documented spelling Id.
  • Values used in URL paths (cn, nregistro, seccion) cannot contain whitespace, /, \, ? or #.
  • pagina returns exactly that page instead of every page.
  • Technical sheet criteria: seccion is N[.N[.N]] with a top level from 1 to 10, texto cannot be blank and contiene is Contiene.SI (or True) or Contiene.NO (or False). They are sent as a JSON body, and the search is retried like a read.

Enumerations

aempsconn.enums holds the closed value sets of the official document. Their values are the CIMA codes.

Enumeration Members
Sust BIOLOGICOS 1, ESTRECHO_MARGEN_PA 2, ESPECIAL_CONTROL 3, RESPIRATORIO_INHALATORIO 4, ESTRECHO_MARGEN_TERAPEUTICO 5
Maestra PRINCIPIOS_ACTIVOS 1, FORMAS_FARMACEUTICAS 3, VIAS_ADMINISTRACION 4, LABORATORIOS 6, CODIGOS_ATC 7, PRINCIPIOS_ACTIVOS_SNOMED 11, FORMAS_FARMACEUTICAS_SIMPLIFICADAS_SNOMED 13, VIAS_ADMINISTRACION_SIMPLIFICADAS_SNOMED 14, MEDICAMENTOS 15, MEDICAMENTOS_COMERCIALIZADOS_SNOMED 16
TipoDocSegmentado FICHA_TECNICA 1, PROSPECTO 2
FormatoContenido JSON, HTML, TEXT (sent as the Accept header)
Contiene SI 1, NO 2
TipoDocumento FICHA_TECNICA 1, PROSPECTO 2, INFORME_PUBLICO_EVALUACION 3, PLAN_GESTION_RIESGOS 4
TipoNota SEGURIDAD 1
TipoCambio NUEVO 1, BAJA 2, MODIFICADO 3
CambioRegistro ESTADO, COMERC, PROSP, FT, PSUM, NOTAS_SEGURIDAD, MATINF, OTROS
TipoFoto MATERIALAS, FORMAFARMAC

In responses, a code that is not in the enumeration stays a plain int or str, so a new CIMA value never breaks parsing.

Models

aempsconn.models holds the pydantic response models: MedicamentosModel (list items), MedicamentoModel (detail), MedicamentoBase (the fields shared by both, their common base class), PresentacionesModel, PresentacionDetalleModel, PresentacionModel, ProblemaSuministroModel, DescripcionClinicaModel, VmpArbolModel, VmppArbolItemModel, NotaModel, MaterialModel, DocumentoMaterialModel, VideoModel, DocumentoModel, FotoModel, ATCModel, PActivoModel, ExcipienteModel, ItemModel, RegistroCambiosModel, SeccionModel and EstadoModel, all based on CimaModel.

  • Attributes keep the CIMA names (viasAdministracion, materialesInf, ...). A few are renamed because the CIMA name is unclear in Python: ItemModel.item_id (id), PActivoModel.pactivo_id and ExcipienteModel.excipiente_id (id), and DocumentoModel.url_html (urlHtml).
  • Only identity fields are required (for example nregistro and nombre of a medicine). Every other field is optional, because CIMA omits documented fields in practice.
  • Dates are timezone-aware datetime values in Europe/Madrid, converted from CIMA's epoch milliseconds (dates before 1970 included). A value that cannot be converted raises ResponseValidationError (from page 2 of a list on, a PaginationError caused by it).
  • Fields that CIMA returns but the models do not declare are kept and readable through model_extra.
  • Where the official document and the live API disagree, both spellings are accepted: NotaModel.referencia (also ref), RegistroCambiosModel.cambio (also cambios, readable as the cambios property) and MaterialModel.video and videos. Fields that CIMA returns without documenting them are marked "observed" in the docstrings.
from aempsconn import AempsConn

with AempsConn() as client:
    med = client.medicamento.get(nregistro="51347")
    if med is not None:
        print(med.estado.aut if med.estado else None)  # aware datetime, Europe/Madrid
        for document in med.docs or []:
            print(document.tipo, document.url, document.secc)
        print(med.model_extra)  # undeclared fields, if CIMA sent any
        print(med.model_dump(mode="json", by_alias=True)["nregistro"])

Configuration

Defaults

Setting Default AempsConn argument
REST base URL https://cima.aemps.es/cima/rest, or the AEMPSCONN_CIMA_BASE_URL environment variable url
HTML documents URL https://cima.aemps.es/cima/dochtml, derived from the base URL documents_url
Connect timeout 5 s timeout
Read timeout (between two received bytes) 30 s timeout
Total time per attempt (headers, body download and redirects included) 60 s timeout
Retries 3 (4 attempts), for reads only retries
Backoff random between 0 and 0.5 s × 2ⁿ (full jitter), at most 10 s retries
Retried failures connection errors, timeouts and HTTP 429, 500, 502, 503, 504 retries
Retry-After honoured (seconds or HTTP date); more than 10 s fails at once retries
Worst case per call 4 × 60 s + 3 × 10 s = 270 s
Response size limit 16 MiB max_response_bytes
Redirects at most 3, same host, never from https to http
Page prefetch 1 (sequential), at most 4 max_workers
TLS verification on verify
Proxy and CA environment variables honoured trust_env
User-Agent aempsconn/<version> (+https://github.com/fqlenos/aempsconn)

The worst case is per call of a single request (a lookup or one page); iterating a list adds one such bound per page. The total limit is enforced on the connection itself from the moment its socket is open, so a server or a proxy that sends data very slowly cannot extend an attempt: the reply of a proxy to CONNECT, the TLS handshakes, the headers and the body all count towards it. Only name resolution (DNS) is left to the operating system and its own timeouts. This holds for direct connections and for http and https proxies, TLS included. Through a SOCKS proxy only the connect and read timeouts apply, so a slow server or proxy can extend an attempt there.

export AEMPSCONN_CIMA_BASE_URL="https://cima.aemps.es/cima/rest"

The environment variable is read when the client is created. A custom base URL must be http or https, without credentials, query string or fragment. When it does not end in /cima/rest, pass documents_url too if you use client.documentos.

Timeouts and retries

from aempsconn import AempsConn, RetryPolicy, Timeout

client = AempsConn(
    timeout=Timeout(connect=5, read=30, total=60),
    retries=RetryPolicy(max_retries=3, backoff_factor=0.5, max_backoff=10, statuses=frozenset({429, 503})),
    headers={"X-Client": "my-application"},
    max_response_bytes=32 * 1024 * 1024,
)
print(client)  # the settings, without secrets
client.close()

strict = AempsConn(timeout=10, retries=0)  # 10 s read, 5 s connect, 20 s total; no retries
strict.close()
  • timeout takes a Timeout, a number of seconds t (connect min(t, 5), read t, total 2t) or a (connect, read) tuple.
  • retries takes a number of retries (0 disables them) or a RetryPolicy. Only reads are retried: every GET and the technical sheet search, which CIMA serves with POST but only reads data.
  • headers adds request headers; Accept, Content-Type and Host are set by the SDK and cannot be changed.
  • The 1.1.1 arguments url, retry, status_force_list and proxies still work (see MIGRATION.md). retries cannot be combined with retry=False or status_force_list.
  • Invalid or conflicting settings raise ConfigurationError when the client is created.

Proxies, TLS and the environment

from aempsconn import AempsConn

client = AempsConn(proxies={"https": "http://user:secret@proxy.example:3128"})
print(client)  # the proxy appears as http://***@proxy.example:3128
client.close()

isolated = AempsConn(trust_env=False)  # ignore proxy and CA bundle environment variables
isolated.close()
  • proxies maps a scheme to a proxy URL, as in requests. Proxy passwords never appear in reprs, logs or error messages.
  • verify is True by default. It also accepts the path of a CA bundle (for example a corporate CA). False disables certificate verification: it is insecure and only meant for tests.
  • With trust_env=True (the default), requests reads the standard environment: HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY, REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE, and credentials from ~/.netrc. Use trust_env=False to make the client depend only on its arguments.
  • A proxy URL that cannot be parsed, for example one from the environment with an invalid port, raises TransportError when a request is sent. The message asks to check the proxy URL (the proxies argument or the HTTP_PROXY/HTTPS_PROXY/ALL_PROXY variables; trust_env=False ignores the environment).

Concurrency

One client can be shared by many threads: its configuration cannot change after creation, the connection pool is shared and no cookies or other per-request state are kept. A PagedResult belongs to one thread. Prefetching (max_workers from 2 to 4) requests the following pages of a result in parallel and still yields them in order. Concurrent threads and prefetch add up, so keep the total small (see fair use).

from concurrent.futures import ThreadPoolExecutor

from aempsconn import AempsConn

with AempsConn() as client, ThreadPoolExecutor(max_workers=4) as pool:
    nregistros = ["51347", "68167", "83867", "83865"]
    for med in pool.map(lambda nregistro: client.medicamento.get(nregistro=nregistro), nregistros):
        print(med.nombre if med else None)

After close(), or after the with block, any call raises ClientClosedError.

Logging

The SDK logs through the aempsconn logger and adds no handlers. DEBUG records each request (method, endpoint, query parameters, attempt, status and time); WARNING records each retry with its reason and delay. Headers and proxy URLs are never logged.

import logging

logging.getLogger("aempsconn").setLevel(logging.DEBUG)

Exceptions

Every SDK error derives from AempsConnError and is importable from aempsconn. The original error is chained (__cause__); when its text may contain a proxy password, as with an invalid proxy URL, a copy that names its type and keeps its message without credentials is chained instead. Messages name the operation (for example GET medicamentos), never contain credentials and include at most 200 sanitised characters of a response body.

AempsConnError
├── ConfigurationError (ValueError)     invalid or conflicting client settings
├── QueryValidationError (ValueError)   invalid parameters, before sending; .parameter, .accepted
├── ClientClosedError                   the client was used after close()
├── TransportError                      network failure; .method, .endpoint
│   ├── CimaTimeoutError                connect, read or total limit exceeded
│   └── CimaConnectionError             DNS, connection, TLS or proxy failure
├── ResponseError                       unusable response; .method, .endpoint, .status_code
│   ├── HTTPStatusError                 non-2xx status after the retries; .body_excerpt
│   ├── UnexpectedContentTypeError      unexpected content type; .expected, .received
│   ├── ResponseTooLargeError           body over the size limit; .limit
│   ├── ResponseDecodeError             malformed JSON or text
│   ├── ResponseValidationError         payload that does not fit the model
│   └── RedirectError                   refused redirect (other host, port or scheme, https to http, credentials,
│                                       invalid URL, too many)
└── PaginationError                     later page failed or inconsistent page; .method, .endpoint, .page

When the first page of a list cannot be retrieved, or its results do not fit the model, nothing has been returned yet, so the original error is raised (for example HTTPStatusError or ResponseValidationError). A failure on a later page raises PaginationError, with the original error as its cause. Its message names the operation, the page and the cause, for example GET medicamentos: page 2 could not be retrieved: CIMA returned HTTP 503 after 4 attempts (page: 2), and a page with the wrong number of results also sets .expected and .received. A failed result keeps raising the same error; call get(...) again to retry.

The message of ResponseValidationError names where the payload does not fit the model and why (for example resultados.0.nregistro: missing), never a value of the response. The pydantic error chained as its cause (__cause__) may include fragments of the response, so a logged traceback can contain them too.

API coverage

All 18 documented operations of the CIMA REST API v1.23 are implemented, with every documented parameter. Two additional variants are not implementable, for the reasons given below, and downloading the files linked from responses is out of scope.

Operation SDK call Status
GET medicamentos client.medicamentos.get(...) Implemented
GET medicamento client.medicamento.get(nregistro=... | cn=...) Implemented
POST buscarEnFichaTecnica client.buscar_en_ficha_tecnica.get(criterios) Implemented
GET presentaciones client.presentaciones.get(...) Implemented
GET presentacion/{cn} client.presentacion.get(cn=...) Implemented
GET psuministro client.psuministro.get() Implemented
GET psuministro/{cn} client.psuministro.get(cn=...) Implemented
psuministro with other filters — Not implementable: the document describes no parameters for it apart from pagina
GET vmpp client.vmpp.get(...), tree view with modoArbol=True Implemented (tree shape observed, not documented)
GET notas/{nregistro} and GET notas?nregistro= client.notas.get(nregistro=...); the 1.1.1 NotaFilter uses the query form Implemented
GET materiales/{nregistro} and GET materiales?nregistro= client.materiales.get(nregistro=...); the 1.1.1 MaterialFilter uses the query form Implemented
GET docSegmentado/secciones/{tipoDoc} client.doc_segmentado.secciones(...) Implemented
GET docSegmentado/contenido/{tipoDoc} client.doc_segmentado.contenido(...), as JSON, HTML or text Implemented
GET dochtml/ft/{nregistro}/FichaTecnica.html, also by section client.documentos.ficha_tecnica(nregistro, seccion=None) Implemented
GET dochtml/p/{nregistro}/Prospecto.html, also by section client.documentos.prospecto(nregistro, seccion=None) Implemented
GET maestras client.maestras.get(maestra=...) Implemented
GET registroCambios client.registro_cambios.get(fecha=...) Implemented
POST registroCambios — Not implementable: the document describes no request body, and a form request returns an empty response (HTTP 204)
Downloading the PDFs and images linked from responses — Not applicable: not an API operation; the URLs are exposed as model fields

Behaviour that CIMA shows but does not document is handled and marked as such: the pagination envelope (totalFilas, pagina, tamanioPagina, resultados), the * wildcard in text parameters, the tree shape of vmpp with modoArbol, and fields such as labcomercializador, generico or tipoProblemaSuministro.

CIMA data and packaging regulation

CIMA returns registry data: registration numbers, national codes (cn), names, laboratories, authorisation status and dates, prescription conditions (cpresc), flags such as triangulo (additional monitoring), conduc (affects driving) or huerfano, active ingredients, excipients, ATC codes, presentations, supply problems, safety notes, informational materials, the technical sheet and the leaflet, and links to documents and photos of the packaging.

Much of what appears on a medicine's packaging is defined by the packaging regulation and is not returned by CIMA: the Braille text, the cupón precinto, the check digit printed with the national code, and the pictograms, symbols and legends that the regulation requires. The SDK does not compute or infer any of them. The facts behind some of them are available as data (for example conduc or cpresc), but how they must appear on the packaging is a regulatory matter outside the API. The AEMPS infographic "Infografía del envase del medicamento" summarises those elements; the CIMA API reference is the official CIMA REST API document.

Security

  • TLS certificates are verified by default and the default base URL is HTTPS. verify=False is an explicit, insecure opt-in.
  • Every request has connect, read and total time limits, and retries are bounded (see defaults).
  • Base URLs are validated: http or https only, no credentials, query string or fragment. Redirects are followed only to the same host, never from https to http, and at most 3 times; a Location that is not a valid URL is refused.
  • Response bodies are limited to 16 MiB by default, the content type must match the requested format, and malformed JSON raises an SDK error.
  • Values placed in URL paths are validated and percent-encoded, and query values are validated before sending.
  • Proxy passwords and header values never appear in reprs, logs or error messages; error messages include at most 200 sanitised characters of a response body.
  • Cookies are refused: the API does not need them, and storing them would be state shared between threads.
  • Only the aempsconn logger is used, with no handlers, and headers and proxy URLs are never logged.
  • trust_env=True lets environment variables and ~/.netrc configure proxies, CA bundles and credentials; use trust_env=False in environments you do not control.
  • Please report suspected vulnerabilities privately to the maintainer instead of opening a public issue.

Migrating from 1.1.1

Version 2.0.0 keeps the 1.1.1 imports, constructor arguments and filter objects working, with a DeprecationWarning for the old import paths (aempsconn.aemps, aempsconn.filter, aempsconn.objects, aempsconn.modules). They will be removed no earlier than 3.0. aempsconn.utils was internal and has been removed. Dates, "not found" results, pagination, validation, errors and some model fields behave differently; the migration guide lists every change with before and after examples.

from aempsconn import AempsConn  # was: from aempsconn.aemps import AempsConn
from aempsconn.query import MedicamentosFilter  # was: from aempsconn.filter import MedicamentosFilter

with AempsConn() as client:
    for med in client.medicamentos.get(filter=MedicamentosFilter().nombre.startswith(value="meto")):
        print(med.nombre)

Development

The project uses Poetry and a Makefile. make check is the complete validation gate and the only command the CI runs; make build runs it before building.

git clone https://github.com/fqlenos/aempsconn.git
cd aempsconn
make install
make check
make build
Target What it does
make install installs the package with the dev and security dependency groups
make format formats the code and applies safe lint fixes
make config validates pyproject.toml and poetry.lock
make lint Ruff formatting check and lint rules
make typecheck mypy in strict mode over the package and the tests
make security Bandit over the source, and pip-audit over the installed dependencies (needs network access)
make test unit and integration tests with coverage (at least 90%)
make package-check builds into a temporary directory and checks the distributions with twine and check-wheel-contents
make check all of the above, in that order
make build make check, then the distributions in dist/
make e2e end-to-end workflow tests
make live smoke tests against the live CIMA API (network)

Install the Git hooks with poetry run pre-commit install.

Test levels

  • tests/unit: pure unit tests, no HTTP.
  • tests/integration: the public API against mocked HTTP (responses) with fixtures trimmed from real CIMA responses in tests/fixtures/cima. They check the exact requests sent and the parsed results, and run every example of the READMEs and the migration guide.
  • tests/e2e (marker e2e): complete public workflows, meant to run against the installed wheel.
  • tests/live (markers live and enable_socket): a small number of real requests to CIMA (at most 20). They are opt-in and never part of make check.

Network access is blocked during the tests (pytest-socket) except in tests/live, and the e2e and live markers are deselected by default.

Releases are built by the release workflow on a v*.*.* tag: one job runs make build, and a separate publish job uploads the artifacts with the PYPI secret, which no other job can read. For maintainers, PyPI trusted publishing (OpenID Connect) is recommended over the API token: once a trusted publisher is configured on PyPI for this repository and workflow, the publish job only needs permissions: id-token: write and the token can be removed.

Contributing

Pull requests are welcome. For larger changes, please open an issue first to discuss them. Before sending a pull request:

  • run make check;
  • add or update tests: unit tests for logic, integration tests with recorded CIMA responses for endpoints;
  • keep CIMA's parameter and field names, and follow the official document;
  • update README.md and README.es.md together, and MIGRATION.md for behaviour changes.

License

MIT. See LICENSE.

Disclaimer

This library is not official and is not affiliated with or endorsed by AEMPS. The data comes from the public CIMA service; check the official sources before using it for clinical or regulatory decisions. Spanish names are kept on purpose, so that the SDK matches the official API and its documentation.

Metadata

Release files for aempsconn 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aempsconn 2.0.0
File Size Uploaded Provenance Actions
aempsconn-2.0.0.tar.gz 111.0 kB Without provenance Details for aempsconn-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aempsconn 2.0.0
File Interpreter ABI Platform Actions
aempsconn-2.0.0-py3-none-any.whl Python 3 none any Details for aempsconn-2.0.0-py3-none-any.whl

Total release size: 229.1 kB

Release files / aempsconn-2.0.0.tar.gz

Download URL aempsconn-2.0.0.tar.gz
Size 111.0 kB
Tags Source
SHA-256 checksum
How to use checksums
0ddf8daabbd532519ed9dd37764e24e4a3289dd50c27b6cf88ff34e157d9306d
BLAKE2b-256 checksum
How to use checksums
1ef765d5119182b41c13983a2afa2503ece8da087124319e58249e6f29bdfde6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / aempsconn-2.0.0-py3-none-any.whl

Download URL aempsconn-2.0.0-py3-none-any.whl
Size 118.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
085cd6615450fececc3ba7e210d15c0beb5b62dc2489a54ca1db45c8342ad7e2
BLAKE2b-256 checksum
How to use checksums
571cb87d3ad3a3ba0fcd8d1a457590043c550f88882e22d7e5507a657320f8ed
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for aempsconn 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page