| Title: | 'openFDA' API |
|---|---|
| Description: | The 'openFDA' API facilitates access to U.S. Food and Drug Administration (FDA) data on drugs, devices, foodstuffs, tobacco, and more. This package makes the API easily accessible with 'httr2', returning objects which the user can convert to JSON data and parse. The API is described in: Kass-Hout TA, Xu Z, Mohebbi M et al. (2016) <doi:10.1093/jamia/ocv153>. |
| Authors: | Simon Parker [aut, cre, cph] (ORCID: <https://orcid.org/0009-0003-8214-4496>) |
| Maintainer: | Simon Parker <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.1.0.9002 |
| Built: | 2026-05-27 08:11:10 UTC |
| Source: | https://github.com/simpar1471/openfda |
search terms for openFDA API queriesThis function is a helper for constructing search queries. Whilst it handles some of the available formatting for openFDA APIs, it does not recapture all of the search term syntax available to you. To get a full appreciation of the openFDA search syntax, see https://open.fda.gov/apis/advanced-syntax/.
format_search_term(search, exact = TRUE, mode = "or")format_search_term(search, exact = TRUE, mode = "or")
search |
A character vector of length 1 or more. If scalar and unnamed,
it will be assumed that you have already formatted your search string to
work with the API. If named, the vector will be collapsed to include your
various search terms, separated by AND or OR terms based on the value of
|
exact |
A single-length logical vector. When This parameter only applies if |
mode |
A single-length character vector, which defines how searches in
multiple fields should be combined. By default ( This parameter only applies if |
A character vector of the S3 class <AsIS>, with a formatted search
term which can be supplied to openFDA().
This function does not check that you're providing accurate field names or search terms. It is up to you to make sure you've provided correctly spelt fields and search terms.
format_sort_term() performs similar formatting for the sort component
of an openFDA query.
I() generates vectors with the <AsIs> S3 class.
httr2::req_url() documents why I() is applied to the output of this
function.
# Provide a formatted search string and the function will do no formatting format_search_term("openfda.generic_name:verapamil") # Provide a named vector and the function will format it for you format_search_term(c("openfda.generic_name" = "verapamil")) # If providing multiple elements in your search term, use `exact = FALSE` # to prevent the function from surrounding the term with double quotes. format_search_term(c("openfda.generic_name" = "verapamil+amlodipine"), exact = FALSE) # Provide a longer named vector and function will merge these with an OR # operator format_search_term(c("openfda.generic_name" = "verapamil", "openfda.manufacturer_name" = "glaxo*")) # Or you can set the `mode` argument to merge your search terms with an AND # operator format_search_term(c("openfda.generic_name" = "verapamil", "openfda.manufacturer_name" = "glaxo*"), mode = "and")# Provide a formatted search string and the function will do no formatting format_search_term("openfda.generic_name:verapamil") # Provide a named vector and the function will format it for you format_search_term(c("openfda.generic_name" = "verapamil")) # If providing multiple elements in your search term, use `exact = FALSE` # to prevent the function from surrounding the term with double quotes. format_search_term(c("openfda.generic_name" = "verapamil+amlodipine"), exact = FALSE) # Provide a longer named vector and function will merge these with an OR # operator format_search_term(c("openfda.generic_name" = "verapamil", "openfda.manufacturer_name" = "glaxo*")) # Or you can set the `mode` argument to merge your search terms with an AND # operator format_search_term(c("openfda.generic_name" = "verapamil", "openfda.manufacturer_name" = "glaxo*"), mode = "and")
sort terms for openFDA API queriesThis function acts as a helper for constructing a sort term in the openFDA API.
format_sort_term(sort)format_sort_term(sort)
sort |
A single-length character vector of length 1. If unnamed, it will be assumed that you have already formatted your search string to work with the API. If named, the vector will be collapsed to include your field and sorting choice. |
A character vector of the S3 class <AsIS>, with a formatted search
term which can be supplied to openFDA().
This function does not check that you're providing accurate field names or search terms. It is up to you to make sure you've provided correctly spelt fields and search terms.
format_search_term() performs similar formatting for the search
component of an openFDA query.
I() generates vectors with the <AsIs> S3 class.
httr2::req_url() documents why I() is applied to the output of this
function.
# Provide a formatted search string and the function will do no formatting format_sort_term("openfda.generic_name:asc") # Provide a named vector and the function will format it for you format_sort_term(c("openfda.generic_name" = "asc")) # Errors will be thrown if you supply a bad input try(format_sort_term("receivedate:no_order")) try(format_sort_term(c("receivedate" = "ascending")))# Provide a formatted search string and the function will do no formatting format_sort_term("openfda.generic_name:asc") # Provide a named vector and the function will format it for you format_sort_term(c("openfda.generic_name" = "asc")) # Errors will be thrown if you supply a bad input try(format_sort_term("receivedate:no_order")) try(format_sort_term(c("receivedate" = "ascending")))
Send requests to the openFDA API
openFDA( search = "", sort = NULL, count = NULL, limit = 1000, skip = NULL, endpoint = "drug-drugsfda", api_key = get_api_key(), paging = current_openFDA_options()[["openFDA.paging"]], paging_verbosity = current_openFDA_options()[["openFDA.paging_verbosity"]], handle_http_errors = current_openFDA_options()[["openFDA.handle_http_errors"]] )openFDA( search = "", sort = NULL, count = NULL, limit = 1000, skip = NULL, endpoint = "drug-drugsfda", api_key = get_api_key(), paging = current_openFDA_options()[["openFDA.paging"]], paging_verbosity = current_openFDA_options()[["openFDA.paging_verbosity"]], handle_http_errors = current_openFDA_options()[["openFDA.handle_http_errors"]] )
search |
A character vector which will be passed to
|
sort |
A single string or scalar named character vector describing how
to sort the results. The |
count |
A single string denoting a field on which to count results. If
|
limit |
A single integerish value describing the limit on the number of
records to retrieve. An error will be thrown if |
skip |
A single integerish value describing how many records should be skipped. If more records are skipped than are found in your search, the openFDA API will return a 404 error. |
endpoint |
A single-length character vector describing which openFDA
endpoint to target (case-sensitive). By default,
|
api_key |
A single-length character vector with your openFDA API key. By
default this is the result of |
paging |
A single string describing whether results should be paged.
|
paging_verbosity |
A single string describing whether messages about
pagination should be printed to the console.
|
handle_http_errors |
A single string defining how to handle HTTP codes
other than
|
Either an httr2 response object from
httr2::req_perform() or list of these objects, depending on whether
pagination was required. You can use httr2::resp_body_json() to extract
JSON data from these responses.
openFDA() caches its results with memoise::memoise(). Consequently, you
should find that repeated, identical queries run faster than the first query,
assuming you don't change your query parameters.
Kass-Hout TA, Xu Z, Mohebbi M, Nelsen H, Baker A, LEvine J, Johansen E, Bright RA. OpenFDA: an innovative platform providing access to a wealth of FDA's publicly available data J Am Med Inform Assoc 2016, 23(3):596-600. doi:10.1093/jamia/ocv153
Read the docs for set_api_key() to learn how to set your openFDA
API key. Check out format_search_term() to see how input search vectors
are converted to openFDA API searches.
if (httr2::secret_has_key("OPENFDA_KEY")) { set_api_key(httr2::secret_decrypt( "TEaDtqdFMq9_Montij5p9IY6T57IyqkbF8IYFVOpk-ttxotFUNdJSxgccAnkq4nQhplaf-r3deQ", "OPENFDA_KEY" )) resp <- openFDA(search = "openfda.manufacturer_name:gilead*", limit = 2, skip = 10, paging = "never", paging_verbosity = "quiet") # The function returns an `httr2` object print(resp) } # Bad inputs will cause informative errors - here, a bad API key is supplied try( openFDA(search = "openfda.manufacturer_name:gilead*", api_key = "BAD_API_KEY", limit = 1) )if (httr2::secret_has_key("OPENFDA_KEY")) { set_api_key(httr2::secret_decrypt( "TEaDtqdFMq9_Montij5p9IY6T57IyqkbF8IYFVOpk-ttxotFUNdJSxgccAnkq4nQhplaf-r3deQ", "OPENFDA_KEY" )) resp <- openFDA(search = "openfda.manufacturer_name:gilead*", limit = 2, skip = 10, paging = "never", paging_verbosity = "quiet") # The function returns an `httr2` object print(resp) } # Bad inputs will cause informative errors - here, a bad API key is supplied try( openFDA(search = "openfda.manufacturer_name:gilead*", api_key = "BAD_API_KEY", limit = 1) )
User-configurable options used by openFDA, which provide a mechanism for setting default behaviours.
openFDA_options( paging = NULL, paging_verbosity = NULL, handle_http_errors = NULL ) current_openFDA_options()openFDA_options( paging = NULL, paging_verbosity = NULL, handle_http_errors = NULL ) current_openFDA_options()
paging |
A single string used to set the
|
paging_verbosity |
A single string used to set the
|
handle_http_errors |
A single string used to set the
|
For openFDA_options() returns a named character vector with
current option values. This will include the updated option values, if any
have been set.
For current_openFDA_options(), returns a named character
vector with the current values for each openFDA package-level option.
# Print current options by leaving all input args as `NULL`: openFDA_options() # Or specify some options to set these: openFDA_options(paging = "never", handle_http_errors = "silent") # Make sure to give valid option values try(openFDA_options(paging = "bad-value")) # If you set an option using `options()` and it is not valid, you will # invoke errors try( rlang::with_options(openFDA.paging = "no", current_openFDA_options()) )# Print current options by leaving all input args as `NULL`: openFDA_options() # Or specify some options to set these: openFDA_options(paging = "never", handle_http_errors = "silent") # Make sure to give valid option values try(openFDA_options(paging = "bad-value")) # If you set an option using `options()` and it is not valid, you will # invoke errors try( rlang::with_options(openFDA.paging = "no", current_openFDA_options()) )
Get and set your openFDA API keys
set_api_key(api_key, user = "openFDA") get_api_key(user = "openFDA")set_api_key(api_key, user = "openFDA") get_api_key(user = "openFDA")
api_key |
A single-length character vector with your openFDA API key. Do not pass the key in as a parameter in your scripts, though: see the 'Setting an openFDA API key' section below for more information. You can generate an API key on the FDA website. |
user |
A single-length character vector, used as the |
For set_api_key(), returns NULL invisibly. The function is
called for its side effect: to store the openFDA API key securely using
keyring::key_set().
For get_api_key(), returns the API key as a single string. An error
will be thrown if no key is found or if the returned key is an empty string
("").
API keys are the sort of thing that should be stored securely. For that
reason, set_api_key() and get_api_key() utilise the
keyring package for storing/retrieving the API
key. It is best practice not to set your API key by passing it directly to
set_api_key(), or you risk exposing it either in your scripts or in
.Rhistory.
Instead, start an interactive R session and run set_api_key(). R will
prompt you to enter your API key, which will then be stored for future use
without logging the key somewhere unsecure.
As for the key itself? It will be stored securely using keyring::key_set().
Once set on a machine, you shouldn't need to run set_api_key() again.
If your current keyring backend supports named keyrings,
then when using set_api_key() for the first time you will be prompted to
create a new keyring called "openFDA" using keyring::keyring_create().
When asked to do this, you will need to enter a password which can be used to
'lock' and 'unlock' this new keyring (see keyring::keyring_lock() for
details). However, you shouldn't need to use this password in the future, as
the keyring will remain unlocked unless you use keyring::keyring_lock() to
lock the "openFDA" keyring.
# Set your openFDA API key with `set_api_key()` api_key <- "example_api_key" set_api_key(api_key) # Retrieve it with `get_api_key()` get_api_key() # An error will be thrown you try to set your API key to an empty string. try(set_api_key(""))# Set your openFDA API key with `set_api_key()` api_key <- "example_api_key" set_api_key(api_key) # Retrieve it with `get_api_key()` get_api_key() # An error will be thrown you try to set your API key to an empty string. try(set_api_key(""))