PDF VectorPDF Vector
Back to all articles

Integrate Academic APIs Into Your Web App

Add paper search to a web app: a backend route across 8 databases, pagination, caching, 429 handling, DOI lookups, full text as Markdown and citations.

Integrate Academic APIs Into Your Web App

Adding paper search to a web app takes one backend route, not a research project. The browser calls your server, your server calls an academic API with a secret key, and you return a small, cached JSON response the UI can render. The parts that take thought are the ones demos skip: how pagination works when several databases answer one query, what to cache and for how long, what to do when a provider is rate limited, and how to turn a search hit into a paper page with full text and a citation. This guide builds each piece in TypeScript with PDF Vector's academic API, using the exact parameter and field names from the API contract.

The architecture in one picture

Browser ──GET /api/papers?q=...&page=2──▶ Your backend route ──POST /api/academic/search──▶ PDF Vector
   ▲                                          │   (API key lives here)                        │
   └────────── small JSON, cached ◀───────────┴── cache (memory / Redis) ◀── merged results ◀─┘
                                                                    from Semantic Scholar, PubMed, arXiv,
                                                                    OpenAlex, Europe PMC, ERIC, Crossref,
                                                                    Google Scholar

Three rules follow from this layout:

  1. The API key never reaches the browser. Every call goes through your server, which also lets you rate limit your own users.
  2. Your route defines its own response shape. Return only the fields your UI renders. That keeps payloads small and lets you change providers later without touching the frontend.
  3. Cache at the route. Many users run the same queries, and paper metadata changes slowly.

These are the operations a typical research feature uses:

OperationEndpointSDK methodCredits
SearchPOST /api/academic/searchclient.academic.search2 per request, any number of providers
Fetch by IDPOST /api/academic/fetchclient.academic.fetch2 per request, up to 100 IDs
Parse full textPOST /api/academic/parseclient.academic.parseper page: nano 1, mini 2, pro 4, max 8
Paper graphPOST /api/academic/paperGraphclient.academic.paperGraphfrom 2, scaling with result size
Similar papersPOST /api/academic/similarPapersclient.academic.similarPapers3 per request
Find citationsPOST /api/academic/findCitationsclient.academic.findCitations2 per sentence

Install the SDK and put the key in an environment variable:

npm install @pdfvector/client
export PDFVECTOR_API_KEY="your-key-from-app.pdfvector.com"

Step 1: A search route

The examples use a Next.js App Router route handler, but nothing depends on Next.js: the same code works in Express, Hono or a Cloudflare Worker. First, a shared client and the shape your UI will receive:

// lib/pdfvector.ts
import { createClient } from "@pdfvector/client";

export const pv = createClient({ apiKey: process.env.PDFVECTOR_API_KEY! });

export type PaperHit = {
  title: string;
  authors: string[];
  year: number | null;
  doi: string | null;
  abstract: string | null;
  citations: number | null;
  pdfURL: string | null;
  link: string | null;
  provider: string | null;
};

Now the route. It validates input, maps a page number to the API's offset, and trims each result to the fields above:

// app/api/papers/route.ts
import { BadRequestError, PaymentRequiredError, TooManyRequestsError } from "@pdfvector/client";
import { pv, type PaperHit } from "@/lib/pdfvector";
import { cached, searchKey } from "@/lib/cache"; // Step 3
import { withRetry } from "@/lib/with-retry"; // Step 4

const PAGE_SIZE = 10; // per provider
const ALLOWED = ["semantic-scholar", "pubmed", "arxiv", "openalex", "europe-pmc", "eric", "crossref", "google-scholar"] as const;
type Provider = (typeof ALLOWED)[number];

export async function GET(request: Request) {
  const params = new URL(request.url).searchParams;
  const q = (params.get("q") ?? "").trim();
  const page = Math.max(1, Number(params.get("page") ?? "1") || 1);
  const providers = (params.get("providers") ?? "semantic-scholar,openalex")
    .split(",")
    .filter((p): p is Provider => (ALLOWED as readonly string[]).includes(p));
  const yearParam = params.get("yearFrom");
  const yearFrom = yearParam ? Number(yearParam) : undefined;

  if (q.length === 0 || q.length > 400) {
    return Response.json({ error: "Query must be 1 to 400 characters." }, { status: 400 });
  }
  if (yearFrom !== undefined && (!Number.isInteger(yearFrom) || yearFrom < 1900 || yearFrom > 2100)) {
    return Response.json({ error: "yearFrom must be a year between 1900 and 2100." }, { status: 400 });
  }
  const useProviders: Provider[] = providers.length ? providers : ["semantic-scholar"];

  let result;
  try {
    result = await cached(
      searchKey(q, useProviders, page, yearFrom),
      24 * 60 * 60 * 1000,
      () =>
        withRetry(() =>
          pv.academic.search({
            query: q,
            providers: useProviders,
            limit: PAGE_SIZE,
            offset: (page - 1) * PAGE_SIZE,
            yearFrom,
            fields: ["title", "authors", "year", "doi", "abstract", "totalCitations", "pdfURL", "providerURL", "provider"],
          }),
        ),
      (r) => !r.errors?.length, // never cache partial results
    );
  } catch (error) {
    if (error instanceof BadRequestError) return Response.json({ error: error.message }, { status: 400 });
    if (error instanceof TooManyRequestsError) return Response.json({ error: "Too many searches, try again shortly." }, { status: 429 });
    if (error instanceof PaymentRequiredError) {
      // Your PDF Vector account is out of credits or on a billing hold: alert yourself, not the user.
      console.error(error.reasonCode, error.message);
      return Response.json({ error: "Search is temporarily unavailable." }, { status: 402 });
    }
    console.error(error);
    return Response.json({ error: "Search failed." }, { status: 500 });
  }

  const hits: PaperHit[] = result.results.map((p) => ({
    title: p.title ?? "Untitled",
    authors: (p.authors ?? []).map((a) => a.name),
    year: p.year ?? null,
    doi: p.doi ?? null,
    abstract: p.abstract ?? null,
    citations: p.totalCitations ?? null,
    pdfURL: p.pdfURL ?? null,
    link: p.providerURL ?? null,
    provider: p.provider ?? null,
  }));

  return Response.json({
    page,
    hits,
    estimatedTotal: result.estimatedTotalResults,
    partial: (result.errors ?? []).map((e) => e.provider),
  });
}

Details that matter in the contract:

  • query is 1 to 400 characters. providers defaults to ["semantic-scholar"].
  • limit is per provider, 1 to 100, default 20. With two providers and limit: 10, one page can hold up to 20 results.
  • yearFrom and yearTo accept years from 1900 to 2100.
  • The citation count field is totalCitations. If you omit fields, you get every field except providerData.

Step 2: Pagination across several providers

offset is also applied per provider, so page n means "skip (n - 1) × limit results in each source, then merge". The API merges the lists from all providers and ranks them by relevance to the query before returning them. Three consequences for your UI:

  • Pages are not fixed-size. A provider can run out of results before the others, so page 5 may hold fewer items than page 1. Stop showing "next" when a page comes back empty, not when it is shorter than expected.
  • estimatedTotalResults is an estimate. It adds up the totals reported by each provider, and the same paper can be counted by more than one of them. Show it as "about 12,000 results", or not at all.
  • The same paper can appear twice. Results are merged and ranked, not deduplicated, so a paper indexed by both Semantic Scholar and OpenAlex can come back from each. Group hits by DOI (or by a normalized title when there is no DOI) before rendering:
function groupByWork(hits: PaperHit[]): PaperHit[] {
  const seen = new Map<string, PaperHit>();
  for (const hit of hits) {
    const key = hit.doi?.toLowerCase() ?? hit.title.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
    const existing = seen.get(key);
    // Keep the record with more metadata: a PDF link and a citation count win.
    if (!existing || (!existing.pdfURL && hit.pdfURL) || (existing.citations == null && hit.citations != null)) {
      seen.set(key, hit);
    }
  }
  return [...seen.values()];
}

Grouping happens per page. A duplicate can still land on a later page; for an infinite-scroll UI, keep the set of seen keys on the client and skip repeats as pages arrive.

Deep pagination is rarely worth it. Users look at the first few pages, then refine the query. Offer filters (year range, source) instead of page 40.

Step 3: Cache before you scale

Every search costs 2 credits, whatever the number of providers. Caching is how you keep that predictable. A few numbers to plan with:

  • 10,000 uncached searches a month = 10,000 × 2 = 20,000 credits, which fits in the Pro plan's 100,000 monthly credits but not in Basic's 3,000.
  • If half of those requests repeat a query from the last day, a cache with a 24-hour TTL saves about 5,000 × 2 = 10,000 credits.

Normalize the key so trivial differences do not miss the cache: lowercase, collapse whitespace, sort the provider list, include page and filters.

// lib/cache.ts: in-memory TTL cache; use Redis or your platform's KV in production
const store = new Map<string, { value: unknown; expires: number }>();

export async function cached<T>(
  key: string,
  ttlMs: number,
  load: () => Promise<T>,
  shouldCache: (value: T) => boolean = () => true,
): Promise<T> {
  const hit = store.get(key);
  if (hit && hit.expires > Date.now()) return hit.value as T;
  const value = await load();
  if (shouldCache(value)) store.set(key, { value, expires: Date.now() + ttlMs });
  return value;
}

export function searchKey(q: string, providers: string[], page: number, yearFrom?: number) {
  const norm = q.toLowerCase().replace(/\s+/g, " ").trim();
  return `search:${norm}:${[...providers].sort().join(",")}:${page}:${yearFrom ?? ""}`;
}

The route in Step 1 already wraps the API call in cached(searchKey(...), 24 * 60 * 60 * 1000, load, shouldCache). Suggested lifetimes:

DataTTLWhy
Search results6 to 24 hoursNew papers appear daily, but a query's top results change slowly
Paper metadata from fetch7 to 30 daysTitles and authors are stable; citation counts drift slowly
Parsed full textIndefinitely, keyed by DOI or arXiv IDA published PDF does not change; re-parse only for a new version

Do not cache responses that contain errors: a partial result from a provider outage should not be served for a day after the provider recovers. That is what the shouldCache predicate (r) => !r.errors?.length in the route does.

Step 4: Rate limits, partial results and 429s

Two different things can be "rate limited", and they need different handling.

An upstream database fails or throttles. The search still succeeds. The response lists the failed providers in errors (each with provider, message and an optional code), and results contains only papers from the providers that answered. Credits are the same either way. The route above passes the failed providers to the UI as partial, so you can show a quiet note such as "PubMed did not respond; results may be incomplete" instead of pretending the list is complete.

Your own calls exceed a limit. The SDK throws a TooManyRequestsError (status 429) with retryAfterSeconds, limit and resetAt when the server provides them. Retry once after the stated delay, then give up and tell the user. Out-of-credit or billing problems arrive as PaymentRequiredError (402) and should never be retried.

// lib/with-retry.ts
import { isPDFVectorError, PaymentRequiredError, TooManyRequestsError } from "@pdfvector/client";

export async function withRetry<T>(call: () => Promise<T>, attempts = 3): Promise<T> {
  for (let i = 1; ; i++) {
    try {
      return await call();
    } catch (error) {
      if (error instanceof PaymentRequiredError) throw error; // credits or billing: alert, don't retry
      const retryable =
        error instanceof TooManyRequestsError || (isPDFVectorError(error) && error.retryable);
      if (!retryable || i >= attempts) throw error;
      const waitSeconds =
        error instanceof TooManyRequestsError && error.retryAfterSeconds
          ? error.retryAfterSeconds
          : 2 ** i + Math.random(); // exponential backoff with jitter
      await new Promise((r) => setTimeout(r, waitSeconds * 1000));
    }
  }
}

Inside a web request, keep the total wait short: a user will not wait 30 seconds for search results. For background jobs, such as nightly enrichment of a reading list, longer waits are fine.

Protect yourself from your own users as well. A per-user limit on your route (for example a token bucket in Redis) stops one script from spending your monthly credits, and debouncing the search box so you only query after the user stops typing for 300 to 500 ms removes most wasted calls.

Step 5: A paper page from a DOI

Search results link to a detail page. When a user lands there from a bookmark, a citation or a pasted DOI, you have an identifier, not a search hit. Academic Fetch resolves identifiers directly: DOIs, PubMed IDs, arXiv IDs, Semantic Scholar IDs, ERIC IDs, Europe PMC IDs and OpenAlex IDs, up to 100 per request, for 2 credits per request.

// app/api/papers/[...id]/route.ts (catch-all, because DOIs contain "/")
import { pv } from "@/lib/pdfvector";
import { cached } from "@/lib/cache";

export async function GET(_req: Request, { params }: { params: Promise<{ id: string[] }> }) {
  const { id } = await params;
  const paperId = id.map(decodeURIComponent).join("/"); // /api/papers/10.1038/nature12373

  const result = await cached(`fetch:${paperId.toLowerCase()}`, 7 * 24 * 60 * 60 * 1000, () =>
    pv.academic.fetch({
      ids: [paperId],
      fields: ["title", "authors", "year", "date", "doi", "abstract", "totalCitations", "totalReferences", "pdfURL", "providerURL", "provider"],
    }),
  );

  const paper = result.results[0];
  if (!paper) {
    const reason = result.errors?.[0]?.error ?? "Not found";
    return Response.json({ error: reason }, { status: 404 });
  }
  return Response.json({ paper, source: paper.detectedProvider });
}

Each result carries the original id you sent and the detectedProvider that resolved it. IDs that cannot be resolved come back in errors with id and error, so a batch of 100 never fails as a whole because one DOI is wrong.

Batching matters for reading lists. Importing a user's 80-item bibliography is one fetch call (2 credits), not 80.

Step 6: Full text as Markdown

Abstracts are enough for a results list. For reading view, highlighting, summaries or question answering, you need the paper's text. Academic Parse takes an id or a provider url (exactly one of them), finds a public PDF and returns Markdown. With includePages: true you also get a pages array of { pageNumber, markdown }, which is what you need to show page-accurate citations later.

import { NotFoundError } from "@pdfvector/client";
import { pv } from "@/lib/pdfvector";

export async function getFullText(doi: string) {
  try {
    const paper = await pv.academic.parse({ id: doi, model: "auto", includePages: true });
    // Store paper.markdown and paper.pages keyed by DOI; this is the expensive call.
    return {
      title: paper.title,
      pdfURL: paper.pdfURL,
      pageCount: paper.pageCount,
      credits: paper.credits,
      pages: paper.pages ?? [],
    };
  } catch (error) {
    // NotFoundError covers NoPublicPDFError (no open-access copy), AcademicPaperNotFoundError
    // (unknown ID) and PDF_NOT_FETCHABLE (no copy could be downloaded).
    if (error instanceof NotFoundError) {
      return null; // show the abstract and a link to the publisher
    }
    throw error;
  }
}

Cost is per page at the tier that runs: a 14-page paper on mini is 14 × 2 = 28 credits. With auto, a text PDF that is read without OCR is billed at most at the mini rate. If no open-access copy can be found or downloaded, the call fails with a typed error and no credits are charged, so your UI should fall back to the abstract.

Parse on demand (when a user opens the reading view) or in a background queue, never inside the search route. A long paper can take a while; for batch jobs pass callback: { url } and the API returns 202 immediately, then POSTs the result to your webhook.

Step 7: Showing citations

Researchers judge a tool by how it handles references. Three features cover most needs.

A formatted reference for every paper. Build it from the metadata you already have. A simple APA-style formatter:

type Meta = { title?: string | null; authors?: { name: string }[] | null; year?: number | null; doi?: string | null };

export function formatReference(p: Meta): string {
  const names = (p.authors ?? []).map((a) => a.name);
  const authors =
    names.length === 0 ? "Unknown author" :
    names.length <= 2 ? names.join(" & ") :
    `${names[0]} et al.`;
  const year = p.year ? `(${p.year})` : "(n.d.)";
  const doi = p.doi ? ` https://doi.org/${p.doi}` : "";
  return `${authors} ${year}. ${p.title ?? "Untitled"}.${doi}`;
}

Metadata is sometimes incomplete (no year, no DOI, unusual author strings), so format defensively and let users copy the DOI link, which is the most reliable identifier.

"Cited by" and "References" tabs. Paper Graph returns the seed paper, the citations (papers that cite it) and references (papers it cites), with citationsLimit and referencesLimit up to 1,000 each and separate offsets for paging:

const graph = await pv.academic.paperGraph({
  id: "10.48550/arXiv.1706.03762",
  citationsLimit: 25,
  referencesLimit: 25,
  fields: ["title", "authors", "year", "doi", "totalCitations"],
});
console.log(graph.totalCitations, graph.citations.length, graph.references.length);

For "more like this", Similar Papers ranks related work by citation-network similarity and returns each publication with a similarity score.

Citation suggestions while writing. If your app has an editor, Find Citations splits a paragraph (up to 5,000 characters) into sentences and returns scored candidate papers for each sentence. It costs 2 credits per sentence, so a five-sentence paragraph is 5 × 2 = 10 credits. Trigger it on an explicit button press, not on every keystroke.

Before you ship: test with real queries

Feature lists tell you little about search quality for your users. Before launch:

  1. Collect 20 to 50 real queries from your users or from the kind of assignments and projects your platform supports, including messy ones: pasted titles, acronyms, author plus topic.
  2. Run each against different provider sets. Biomedical queries usually need PubMed or Europe PMC; education topics benefit from ERIC; preprints in computer science and physics come from arXiv; Semantic Scholar and OpenAlex are broad defaults.
  3. Have a domain expert mark the top results as relevant or not. Count how often the paper they expected appears on page one.
  4. Check the failure cases: queries that return nothing, papers without abstracts, results without PDF links.

Pick default providers per audience from this exercise rather than querying all eight on every request. Fewer providers means faster responses and fewer duplicates to group, at the same 2 credits.

If you want to see the full research-assistant version of this pipeline, with retrieval and grounded answers over parsed papers, read Build an AI Research Assistant With Paper APIs. For the platform-level view (provider coverage, ranking, freshness and cost at scale), see Academic Search Infrastructure That Scales.

FAQ

Can I call the academic API directly from the browser?

No. The API key would be visible to anyone who opens developer tools. Call it from a backend route or serverless function and return only the fields your UI needs.

How does pagination work when I search several databases?

limit and offset apply to each provider. Page n uses offset = (n - 1) × limit, and the API merges and ranks the results. Pages can vary in size, and estimatedTotalResults is the sum of the providers' estimates.

Are duplicate papers removed from multi-provider results?

No. The same work can come back from more than one provider. Group results by DOI, or by normalized title when there is no DOI, before you display them.

What happens when one database is down or rate limited?

The request still succeeds with the papers from the providers that answered, and the failed ones are listed in errors. Show that the results are partial and do not cache that response.

How much does a search cost?

2 credits per search request, regardless of how many providers it covers. Fetch is 2 credits per request for up to 100 IDs. Full-text parsing is billed per page, from 1 credit (nano) to 8 credits (max). The free plan includes 100 credits a month.

How do I get the full text of a paper by DOI?

Call Academic Parse with id set to the DOI. It finds an open-access PDF and returns Markdown, plus per-page Markdown with includePages: true. If no public PDF exists, it returns an error and charges nothing. For a one-off download, the free DOI to PDF tool finds an open-access PDF for a DOI in the browser.