How to build a web API for research data and models
When a dataset or model needs an API, which framework to use, and how to design, document, version, secure and host it so results stay reproducible.

- Build an API when data change often, are too big to download whole, or a model must answer other tools; otherwise archive a file with a DOI.
- Use the language your analysis runs in: FastAPI for Python, plumber for R, Django REST framework for curated databases with logins.
- Stable noun-based URLs, paginated lists, plain JSON or CSV and correct status codes make an API usable.
- Return the API, data and model version with every response, and plan who runs the service after the grant.
A web API lets other people and other programs query your research dataset or run your model without downloading files or emailing you. In short: build one when the data change often, are too large to download whole, or when a model has to answer requests from tools you do not control. Use a framework that writes the documentation for you (FastAPI in Python, plumber in R), keep URLs stable, return plain JSON or CSV, and put a version number on both the API and the data behind every response.
An API (application programming interface) on the web is a set of URLs that return data instead of pages. A request such as GET /v1/samples?site=north&year=2025 returns a list of records, and a script in Python, R or JavaScript can use them straight away. Large research infrastructures have worked this way for years: the Ensembl REST API serves genome annotation, and the GBIF API serves biodiversity occurrence records to scripts and apps worldwide.
Most lab APIs start as a weekend project by a PhD student and are fine that way. When the API becomes something partners, clinics or a funder depend on, with logins, uptime promises and several client apps, the work looks more like product engineering than research. At that point some groups hire one of the teams that offer API development services to build and run the outer layer, while the scientists keep ownership of the data model and the analysis code.
When does a research project need an API?
A research project needs an API when people will query the data or the model repeatedly and selectively, not just download it once. If a single archived file answers every reuse case, publish the file instead.
Signs that an API is worth the effort:
- The data keep changing. A sensor network, a field survey or a curated database that grows every week cannot be reissued as a new download each time.
- The data are too big to download whole. Users want one species, one gene or one region, not 400 GB.
- A model has to answer requests. Other tools need predictions from your trained model without installing your environment.
- Several front ends share one source. A dashboard, a mobile data-collection app and a partner's pipeline all read the same records.
- Access must be controlled. Some users may see everything, others only aggregated or anonymised results.
If none of these apply, a versioned file archived with a DOI is simpler and easier to cite. Our guide to archiving code and data with a DOI covers that route.
API, dashboard or science gateway: which do you need?
An API serves machines; a dashboard and a science gateway serve people. Many projects end up with an API underneath and a human interface on top.
| Option | Who uses it | Best for | Typical effort |
|---|---|---|---|
| Archived file with a DOI | Anyone who downloads it | Fixed datasets tied to a paper | Hours |
| Web API | Scripts, pipelines, other apps | Live or large data, model predictions, many clients | Days for a first version, ongoing upkeep |
| Dashboard | People exploring results | Interactive plots and filters for a known audience | Days |
| Science gateway | Researchers running analyses on shared compute | Jobs, accounts, workflows and storage behind a web portal | Months |
For the human-facing options, see our comparison of Streamlit, Dash and Shiny for research dashboards and the guide to building a science gateway.
Which framework should you build it with?
Use the language your analysis code already runs in, and pick a framework that generates an OpenAPI description automatically. The OpenAPI Specification is the standard machine-readable description of an HTTP API; tools turn it into interactive docs and client libraries.
| Framework | Language | Strengths | Watch out for |
|---|---|---|---|
| FastAPI | Python | Input validation with type hints and Pydantic; interactive docs at /docs out of the box | Async code is optional, and mixing it with blocking model calls needs care |
| Flask | Python | Small and familiar; many tutorials | Validation and OpenAPI docs need extra packages |
| Django REST framework | Python | Users, permissions and an admin interface for curated databases | Heavier; worth it when you also need accounts and editing |
| plumber | R | Turns annotated R functions into endpoints; generates OpenAPI docs | Single-threaded by default; plan for several processes under load |
| Express | JavaScript (Node.js) | Good when the front end team already writes JavaScript | Rewriting analysis code in JavaScript is rarely worth it |
For a model trained in Python, FastAPI is the usual starting point. For a curated database with editors and logins, Django REST framework saves you from writing user management yourself. If your model lives in R, plumber avoids a risky port to another language.
What does a minimal research API look like?
A minimal research API has one endpoint per question, validated input and a version field on every response. This FastAPI sketch serves readings from a field station and a model prediction:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="Field station API", version="1.0.0")
DATA_RELEASE = "2025-11" # snapshot the responses come from
MODEL_VERSION = "growth-model 2.3"
class GrowthInput(BaseModel):
temperature_c: float
rainfall_mm: float
@app.get("/v1/stations/{station_id}/readings")
def readings(station_id: str, limit: int = 100):
rows = load_readings(station_id, limit) # your existing code
if rows is None:
raise HTTPException(status_code=404, detail="Unknown station")
return {"data_release": DATA_RELEASE, "items": rows}
@app.post("/v1/predict")
def predict(x: GrowthInput):
y = growth_model(x.temperature_c, x.rainfall_mm) # your existing code
return {"model_version": MODEL_VERSION, "predicted_growth_cm": y}
Run it with uvicorn main:app and FastAPI serves interactive documentation at /docs, generated from the same type hints that validate the input. The functions load_readings and growth_model stand for code you already have; the API is a thin layer over it, not a rewrite.
How should you design the URLs and resources?
Name URLs after the things in your data, keep them stable, and let HTTP methods say what happens. This is the core advice of "Eleven quick tips to build a usable REST API for life sciences" (Tarkowska et al., PLOS Computational Biology, 2018), and it holds in every field.
- Use nouns for resources.
/samples,/samples/{id},/stations/{id}/readings. Avoid verbs such as/getSampleData. - Use query parameters to filter and sort.
/readings?from=2025-01-01&to=2025-03-31&sort=time. - Paginate every list. Return a fixed page size with a link to the next page, so a careless request cannot pull the whole database at once.
- Use identifiers people already know. If your records have DOIs, accession numbers or ORCID iDs, expose them rather than internal database keys.
- Keep model endpoints separate. A prediction endpoint such as
POST /v1/predicttakes input in the request body and returns the prediction with the model version.
Which data formats should the API return?
Return JSON by default, offer CSV for tabular data, and keep domain formats where your field expects them. Researchers will load the response into pandas, R or a spreadsheet, so plain and predictable beats clever.
- JSON for records and nested metadata. Keep field names consistent and document units for every numeric field.
- CSV for tables that people will open in R or a spreadsheet.
- Domain formats such as FASTA, NetCDF or GeoJSON when the tools in your field read them directly.
- Content negotiation. Let clients ask for a format with the
Acceptheader instead of inventing URL suffixes.
Return errors in a consistent JSON shape with a clear message and the right status code: 400 for bad input, 404 for an unknown record, 429 when a client exceeds the rate limit, and 500 only for genuine server faults. A 200 response carrying an error message breaks every client that checks status codes.
How do you keep API results reproducible?
Every response should say which version of the API, the data and the model produced it. Without that, a figure built from your API last spring cannot be traced or rebuilt.
- Version the API. Put a major version in the path (
/v1/) or a header, and never change the meaning of a field inside a version. - Version the data. Add a release identifier or snapshot date to every response, and keep old releases queryable for a stated period.
- Version the model. Return the model name, version and training-data release with each prediction. If you retrain, bump the version.
- Archive releases. Deposit each data release and the API code with a DOI, so papers can cite exactly what they used. Our guide to citing software in papers shows the format.
- Announce changes. Keep a changelog and give users notice before retiring a version.
Packaging the analysis code properly makes this much easier. If the model's preprocessing lives in an installable package with pinned versions, the API and the paper's notebooks call the same code. See our guide to packaging Python research code.
How should you document the API?
Publish the OpenAPI description, an interactive docs page and three or four worked examples in the languages your users write. Every gap in the docs comes back as a support email.
- Quick start. One copy-and-paste request in
curl, Python and R that returns real data. - Field reference. Every field with its type, unit, allowed values and meaning.
- Limits. Page sizes, rate limits and what happens when a client hits them.
- How to cite. The DOI of the data release and of the software, and a suggested citation.
- Contact and status. Where to report problems and where to check whether the service is up.
The same rules apply as for any README; our guide to writing a README for research code has a template you can adapt.
How do you handle access, CORS and sensitive data?
Keep public data public and simple, and put anything sensitive behind real authentication over HTTPS. Do not invent your own login scheme.
- Public, read-only data. No login, but use API keys or rate limits so one runaway script cannot take the service down.
- Restricted data. Use a standard method such as OAuth 2.0 through your institution's identity provider, and log who accessed what.
- Personal or clinical data. Serve only aggregated or de-identified results unless an ethics approval and data agreement say otherwise. Check the rules that apply to you, such as GDPR in Europe or HIPAA in the United States, with your data protection officer.
- CORS. If browser apps on other sites will call your API, return the CORS headers that allow it. Allow all origins only for public, read-only endpoints.
Where should a research API run, and who keeps it up?
Start on infrastructure your institution already supports, and decide before launch who will run the API after the grant ends. Hosting is rarely the hard part; services that nobody owns are what fail.
- Institutional servers or a university cloud are often free to the project and keep data inside approved environments.
- Commercial cloud suits APIs with uneven traffic; our article on cloud computing for research code covers budgets and cost caps.
- Containers make the API portable between those options. Build the image in CI and run the tests from our guide to testing research code before every release.
- Monitoring. A free uptime checker that emails the maintainer is enough for most lab APIs.
Write a short plan for the end of funding: hand the API to a data centre, keep it running in read-only mode, or retire it with notice and leave the archived releases online. Costs for this belong in the grant budget; our piece on funding the maintenance of research software explains how to ask for them.
Who should build it: the lab, an RSE or an outside team?
Match the builder to how long the API must live and how many people depend on it. The scientist who knows the data should always own the data model and the meaning of each field.
- The lab itself for a prototype or an API used by a handful of collaborators.
- A research software engineer when the API supports several projects or must last beyond one PhD; see our guide to research software engineers.
- An outside development team when the API needs accounts, service-level promises, several client apps or integration with clinical or commercial systems. Keep the specification, tests and data dictionary in your repository so the knowledge stays with the project.
What to do this week: ship a first version
- Write down the three questions users most often ask of your data or model. Each becomes an endpoint.
- Sketch the URLs and the JSON for one response, including version fields and units.
- Build those endpoints in FastAPI or plumber against a copy of the data.
- Add tests that call each endpoint and check the response shape.
- Publish the generated docs with a quick start and a citation block.
- Give it to two real users, watch them use it, and fix what confused them before announcing it.
Questions about research APIs
When should a research dataset have an API instead of a download?
Offer an API when the data change often, are too large to download whole, or when other tools need model predictions on demand. A fixed dataset tied to one paper is better published as a versioned file with a DOI, which is simpler to maintain and to cite.
Is FastAPI or Flask better for a research API?
For a new Python API, FastAPI is usually the better start because it validates input from type hints and generates OpenAPI documentation automatically. Flask is fine if your group already knows it, but you will add packages for validation and docs yourself.
Can I build an API for an R model?
Yes. The plumber package turns annotated R functions into web endpoints and generates OpenAPI documentation. It runs one request at a time by default, so run several processes behind a proxy if many users will call it at once.
How do I cite data I retrieved from a research API?
Cite the data release or snapshot the API reports in its responses, using the DOI the provider lists in its documentation, and record the date of your query. If the API returns a version field, include it in your methods section.
Should the API version go in the URL or in a header?
Both work. A version in the path such as /v1/ is easy to see and to test in a browser; a header keeps URLs stable across versions. Pick one, document it, and never change the meaning of a field within a version.
Keep reading. More from the desk.

How to build a science gateway for your research software
A science gateway puts your research code behind a browser so people who cannot install it can still use it. This guide covers when one is worth building, which frameworks to start from and how to keep it running.

Streamlit vs Dash vs Shiny: choosing a dashboard for research data
Streamlit is fastest, Dash gives the most control, Shiny suits R users. A practical comparison for research data, with hosting and reproducibility advice.

How to package Python research code so others can install it
A package gives research code one home, one version and one way in. This guide covers the src layout, pyproject.toml, tests, releases, citation and PyPI.