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
- Redirect the user to our authorization URL
- User authenticates and grants permission to your application
- User is redirected back to your application with an authorization code
- Exchange the authorization code for an access token
- 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.
Scope | Description |
---|---|
trials:read | Read public trial data |
user:read | Read basic user profile information |
user.trials:read | Read user's trial participation data |
user.trials:write | Enroll user in trials and update participation status |
user.data:read | Read user's health data and trial submissions |
user.data:write | Submit 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
/trials
Get a list of clinical trials with optional filtering.
Query Parameters
Parameter | Type | Description |
---|---|---|
condition | string | Filter by medical condition |
status | string | Filter by trial status (recruiting, completed, etc.) |
limit | integer | Number of results to return (default: 20, max: 100) |
offset | integer | Number 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"
/trials/{id}
Get detailed information about a specific clinical trial.
Path Parameters
Parameter | Type | Description |
---|---|---|
id | string | Trial 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.
/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"
/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"
/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
Code | Description |
---|---|
200 - OK | The request was successful. |
400 - Bad Request | The request was invalid or cannot be served. The exact error is explained in the response body. |
401 - Unauthorized | Authentication credentials were missing or incorrect. |
403 - Forbidden | The authenticated user does not have permission to access the requested resource. |
404 - Not Found | The requested resource does not exist. |
429 - Too Many Requests | The rate limit has been exceeded. See the Rate Limiting section for details. |
500, 502, 503, 504 - Server Errors | Something 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 Code | Description |
---|---|
invalid_request | The request was malformed or missing required parameters. |
invalid_auth | Authentication failed due to invalid credentials. |
insufficient_scope | The access token does not have the required scope for the requested operation. |
rate_limit_exceeded | The rate limit for the API has been exceeded. |
server_error | An 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
Plan | Rate Limit | Burst Limit |
---|---|---|
Free | 100 requests/hour | 20 requests/minute |
Basic | 1,000 requests/hour | 100 requests/minute |
Enterprise | 10,000 requests/hour | 1,000 requests/minute |
Rate Limit Headers
The API includes rate limit information in the response headers:
Header | Description |
---|---|
X-RateLimit-Limit | The maximum number of requests you're permitted to make per hour. |
X-RateLimit-Remaining | The number of requests remaining in the current rate limit window. |
X-RateLimit-Reset | The 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.