Back to Developer Portal

API Documentation

Introduction

The FDA.gov v2 API provides programmatic access to clinical trial data, comparative effectiveness information, and outcome labels. This documentation will help you integrate with our API and build powerful healthcare applications.

Base URL

https://api.dfda.earth/v1

All API requests should be made to the base URL above. The API is organized around REST principles and returns JSON-encoded responses.

Authentication

The FDA.gov v2 API supports two authentication methods: API keys for accessing public data and OAuth 2.0 for accessing user-specific data.

API Keys

API keys are used to access public data like clinical trials, outcome labels, and comparative effectiveness data. Include your API key in the Authorization header of all your requests.

API Key Authentication

// Include in all API requests
const headers = {
  'Authorization': 'Bearer YOUR_API_KEY',
  'Content-Type': 'application/json'
};

fetch('https://api.dfda.earth/v1/trials', { headers })
  .then(response => response.json())
  .then(data => console.log(data));

OAuth 2.0

OAuth 2.0 is used to access user-specific data and perform actions on behalf of users. This is required for endpoints that access or modify user data.

OAuth 2.0 Flow

  1. Redirect the user to our authorization URL
  2. User authenticates and grants permission to your application
  3. User is redirected back to your application with an authorization code
  4. Exchange the authorization code for an access token
  5. Use the access token to make API requests on behalf of the user

1. Redirect to Authorization URL

const CLIENT_ID = 'your_client_id';
const REDIRECT_URI = 'https://your-app.com/callback';
const SCOPES = 'user:read user.trials:read';

function redirectToAuth() {
  const authUrl = new URL('https://api.dfda.earth/oauth/authorize');
  authUrl.searchParams.append('client_id', CLIENT_ID);
  authUrl.searchParams.append('redirect_uri', REDIRECT_URI);
  authUrl.searchParams.append('response_type', 'code');
  authUrl.searchParams.append('scope', SCOPES);

  window.location.href = authUrl.toString();
}

2. Exchange Code for Token

// After receiving the code in your redirect URI
async function exchangeCodeForToken(code) {
  const response = await fetch('https://api.dfda.earth/oauth/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code: code,
      redirect_uri: REDIRECT_URI,
      client_id: CLIENT_ID,
      client_secret: 'YOUR_CLIENT_SECRET'
    })
  });

  const data = await response.json();
  // Store tokens securely
  localStorage.setItem('access_token', data.access_token);
  localStorage.setItem('refresh_token', data.refresh_token);

  return data;
}

3. Use Access Token

// Include in API requests that require user authentication
const accessToken = localStorage.getItem('access_token');

const headers = {
  'Authorization': `Bearer ${accessToken}`,
  'Content-Type': 'application/json'
};


fetch('https://api.dfda.earth/v1/user/profile', { headers })
  .then(response => response.json())
  .then(data => console.log(data));

OAuth 2.0 Scopes

Scopes define the specific access permissions your application is requesting. Always request the minimum scopes necessary for your application.

ScopeDescription
trials:readRead public trial data
user:readRead basic user profile information
user.trials:readRead user's trial participation data
user.trials:writeEnroll user in trials and update participation status
user.data:readRead user's health data and trial submissions
user.data:writeSubmit data on behalf of the user

API Endpoints

The FDA.gov v2 API provides several endpoints for accessing different types of data. Below is a comprehensive reference for all available endpoints.

Clinical Trials Endpoints

GET/trials

Get a list of clinical trials with optional filtering.

Query Parameters

ParameterTypeDescription
conditionstringFilter by medical condition
statusstringFilter by trial status (recruiting, completed, etc.)
limitintegerNumber of results to return (default: 20, max: 100)
offsetintegerNumber of results to skip (default: 0)

Example Request

curl -X GET "https://api.dfda.earth/v1/trials?condition=diabetes&limit=2"   -H "Authorization: Bearer YOUR_API_KEY"   -H "Content-Type: application/json"
GET/trials/{id}

Get detailed information about a specific clinical trial.

Path Parameters

ParameterTypeDescription
idstringTrial ID

Example Request

curl -X GET "https://api.dfda.earth/v1/trials/trial-123"   -H "Authorization: Bearer YOUR_API_KEY"   -H "Content-Type: application/json"

User Data Endpoints

These endpoints require OAuth 2.0 authentication with appropriate scopes.

GET/user/profile

Get the authenticated user's profile information.

Required scope: user:read

Example Request

curl -X GET "https://api.dfda.earth/v1/user/profile"   -H "Authorization: Bearer USER_ACCESS_TOKEN"   -H "Content-Type: application/json"
GET/user/trials

Get the authenticated user's trial participation.

Required scope: user.trials:read

Example Request

curl -X GET "https://api.dfda.earth/v1/user/trials"   -H "Authorization: Bearer USER_ACCESS_TOKEN"   -H "Content-Type: application/json"
POST/user/trials/{trial_id}/enroll

Enroll the authenticated user in a specific trial.

Required scope: user.trials:write

Example Request

curl -X POST "https://api.dfda.earth/v1/user/trials/trial-456/enroll"   -H "Authorization: Bearer USER_ACCESS_TOKEN"   -H "Content-Type: application/json"   -d '{
    "consent": true,
    "deposit_payment": {
      "payment_method_id": "pm_123456789"
    }
  }'

Error Handling

The FDA.gov v2 API uses conventional HTTP response codes to indicate the success or failure of an API request. Here's how to handle errors in your applications.

HTTP Status Codes

CodeDescription
200 - OKThe request was successful.
400 - Bad RequestThe request was invalid or cannot be served. The exact error is explained in the response body.
401 - UnauthorizedAuthentication credentials were missing or incorrect.
403 - ForbiddenThe authenticated user does not have permission to access the requested resource.
404 - Not FoundThe requested resource does not exist.
429 - Too Many RequestsThe rate limit has been exceeded. See the Rate Limiting section for details.
500, 502, 503, 504 - Server ErrorsSomething went wrong on our end. Please try again later.

Error Response Format

When an error occurs, the API returns a JSON object with an error field containing details about the error.

Example Error Response

{
  "error": {
    "code": "invalid_request",
    "message": "The 'condition' parameter is required",
    "status": 400,
    "documentation_url": "https://api.dfda.earth/docs/errors#invalid_request"
  }
}

Common Error Codes

Error CodeDescription
invalid_requestThe request was malformed or missing required parameters.
invalid_authAuthentication failed due to invalid credentials.
insufficient_scopeThe access token does not have the required scope for the requested operation.
rate_limit_exceededThe rate limit for the API has been exceeded.
server_errorAn error occurred on the server. Please try again later.

Rate Limiting

To ensure the stability and availability of the API for all users, the FDA.gov v2 API implements rate limiting. The rate limits vary based on your plan.

Rate Limits by Plan

PlanRate LimitBurst Limit
Free100 requests/hour20 requests/minute
Basic1,000 requests/hour100 requests/minute
Enterprise10,000 requests/hour1,000 requests/minute

Rate Limit Headers

The API includes rate limit information in the response headers:

HeaderDescription
X-RateLimit-LimitThe maximum number of requests you're permitted to make per hour.
X-RateLimit-RemainingThe number of requests remaining in the current rate limit window.
X-RateLimit-ResetThe time at which the current rate limit window resets in UTC epoch seconds.

SDKs & Client Libraries

To make integration easier, we provide official SDKs for popular programming languages. These SDKs handle authentication, error handling, and provide a more convenient interface for working with the API.

JavaScript SDK

For Node.js and browser applications

Installation

npm install dfda-js-sdk

# or with yarn
yarn add dfda-js-sdk

Python SDK

For Python applications

Installation

pip install fdav2-sdk

# or with poetry
poetry add fdav2-sdk

Ruby SDK

For Ruby applications

Installation

gem install fdav2-sdk

# or in your Gemfile
gem 'fdav2-sdk'

JavaScript SDK Example

Basic Usage

import { FDAv2Client } from '@fdav2/sdk';

// Initialize with API key for public data
const client = new FDAv2Client({
  apiKey: 'YOUR_API_KEY'
});

// Get clinical trials
async function getTrials() {
  try {
    const trials = await client.trials.list({
      condition: 'diabetes',
      limit: 10
    });
    console.log(trials);
  } catch (error) {
    console.error('Error fetching trials:', error);
  }
}

// Initialize with OAuth for user data
const oauthClient = new FDAv2Client({
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET',
  redirectUri: 'https://your-app.com/callback'
});

// Generate authorization URL
const authUrl = oauthClient.auth.getAuthorizationUrl({
  scopes: ['user:read', 'user.trials:read']
});

// Exchange code for token
async function handleCallback(code) {
  try {
    const tokens = await oauthClient.auth.getToken(code);
    // Store tokens securely
    localStorage.setItem('access_token', tokens.access_token);
    
    // Use the token
    const userClient = new FDAv2Client({
      accessToken: tokens.access_token
    });
    
    const profile = await userClient.user.getProfile();
    console.log(profile);
  } catch (error) {
    console.error('Error:', error);
  }
}

Support & Resources

Need help with the FDA.gov v2 API? Here are some resources to help you get started and resolve any issues you may encounter.

Developer Community

Join our developer community to ask questions, share solutions, and connect with other developers.

GitHub Issues

Report bugs, request features, or contribute to our open-source SDKs on GitHub.

Email Support

Contact our developer support team for assistance with integration issues.

API Status

Check the current status of the API and view any ongoing incidents.