Skip to content

1. API Token Generation

The PharmaKB GraphQL API is accessed by logging into the application, and visiting: https://app.pharmakb.com/api/v1/graphql

This will return an Authorization token which will not expire. Please refer below on how to generate this token and use it.

It is possible to create up to 20 tokens per User.

There are three REST endpoints available (create, revoke, revokeall) through POST methods to manage API Tokens:

endpoint

auth method

description

POST /api/v1/token/create/

basic auth

Sends Authentication Header for server to generate a token using basic auth.

Add a Header to the request:

Authorization: Basic enc_to_base64(UserName:password)

Example:

Username: pharmakb@pharmakb.com

Password: abc123

=> (combine into Authorization Header construct)

pharmakb@pharmakb.com:abc123

=> (server-side tokenization to check access)

cGhhcm1ha2JAcGhhcm1ha2IuY29tOmFiYzEyMw==

=> (add this to the REST API request header)

Authorization: Basic cGhhcm1ha2JAcGhhcm1ha2IuY29tOmFiYzEyMw==

Reference for manual generation:

POST /api/v1/token/revoke/

token

Allows revoking specific token for a user authenticated with a token

 

POST /api/v1/token/revokeall/

basic auth or token

Allows revoking all tokens for a user being authenticated either by a token or by basic auth

To trigger the endpoints use either Linux util Curl or

2. API Token Expiration

A generated API token has no expiration time limit. Tokens can be replaced at any time by using the revoke endpoint and generating a new token.

3. What Is Possible to Query

It is possible to perform any query if it is compliant with the current PharmaKB GraphQL Schema.

To explore PharmaKB GraphQL Schema, please use GraphiQL - an online tool that makes it’s easier to get started with a GraphQL-based API.

In the Docs panel of GraphiQL, also known as the Documentation Explorer, you can go through the schema definitions.

NOTE: you must be logged in PharmaKB to view the content.

Navigate through root Query to get started.

Root Mutation is currently not available for the Users of the PharmaKB GraphQL API.

4. Query Examples

These examples are a few use cases for the PharmaKB API. They are intended to be

NOTE: Examples below don’t contain all available fields possible to query. Please explore PharmaKB GraphQL Schema for more details.

Description

Query

Query variables

Query All Drugs

The result section can contain any set of attributes from Drugtype.

Example: Query common attributes for all drugs.

query DrugSearch($search: String, $offset: Int, $limit: Int) {
  drugs(search: $search, offset: $offset, limit: $limit) {
    matchedCount
    searchMatch {
      matchedField
      matches
    }
    result {
      id
      name
      commonInfo {
        commonName
        inn
      }
    }
  }
}
  

 

Example: Query commercial attributes for all drugs.

query DrugSearch($search: String, $offset: Int, $limit: Int) {
  drugs(search: $search, offset: $offset, limit: $limit) {
    matchedCount
    searchMatch {
      matchedField
      matches
    }
    result {
      id
      name
      commercialInfo {
        therapeuticAreas {
          areaName
          meshId
        }
        atcCodes {
          code
          name
        }
      }
    }
  }
}
  

To get first 100 drugs please set the following variables:

{ "offset": 0, "limit": 100}

Change the limit to get more/fewer drugs.

Change the offset to get next 100 drugs.

Wildcard Searching (any string)

A similar request can be used for searching drugs with any specific piece of text string.

Note: This request allows to search first 100 drugs that contain string “Aba” in its name or in other fields.

{ "search": "Aba", "offset": 0, "limit": 100}

Query a Specific Drug

If you know a Drug name, you can use the drug query to access it which returns Drugtype attributes.

Example: Query adverse events for a specific drug.

query Drug {
  drug(name: "Abacavir") {
    id
    name
    adverseEvents {
      total
      fulfillExpediteCriteria
      seriousEvents {
        total
        eventData {
          category
          count
        }
      }
    }
  }
}

 

Example: Query trends.

query Drug {
  drug(name: "Abacavir") {
    id
    name
    trends {
      databaseSource
      queryTerm
      articlesNumber
      topTerms(category: diseaseOrSyndrome) {
        cui
        name
        overallCount
        timelineData {
          date
          count
        }
      }
    }
  }
}

-

Query All Report Sets

(e.g., COVID-19 Drugs Set)

Example: Get all report sets and their IDs.

query ReportSets {
  reportsets {
    id
    name
  }
}

 

Example: Get more information about each report set.


query ReportSets {
  reportsets {
    id
    name
    description
    drugs {
      id
      name
    }
    totalReportsCount
    accessibleReportsCount
  }
}

-

Query a Specific Report Set

Example: Query a specific report, using a report ID.

query ReportSet {
  reportset(id: 1) {
    id
    name
    description
    drugs {
      id
      name
    }
    totalReportsCount
    accessibleReportsCount
  }
}

 

-

Query User Information

Example: Query user information, using a username.


 query Me {
  me {
    id
    username
    firstName
    lastName
    email
    isStaff
    isActive
    dateJoined
    subscriptiontype {
      level
      started
      expires
    }
    verified
    secondaryEmail
  }
}

-

Query Current Subscription

Example: Query your subscription details.


query Subscription {
  subscription {
    level
    started
    expires
  }
}

-

5. API Access Guide Using Python

This section is intended to be a guide and an example on how to create a token and access the API with this token using requests library from Python.

Token Generation

First step for gaining access to the API is to create an access token string by sending a REST call to PharmaKB:

import requests

url = 'https://app.pharmakb.com/api/v1/token/create/'
r = requests.post(url=url, headers={"Authorization": "Basic <your_basic_auth_string"})

 

The code above will return the following:

{"expiry":null,"token":"<your_generated_token_string>"}

Please save this token string safely for future use for the user.

API Access with Generated Token

After obtaining an access token, it is simple to access the GraphQL API using the query language using the same library:

import requests

query
= { 'query': """ query ReportSets { reportsets { id name } } """, } response = requests.post('https://app.pharmakb.com/api/v1/graphql/', headers={'Authorization': "Token <your_generated_token_string>"}, json=query)

 

This code will return a response like the following:

{"data":
 {"reportsets":[
  {"id":"2","name":"COVID-19"},
  {"id":"3","name":"FDA Novel Drug Approvals 2020"},
  {"id":"5","name":"SARS-CoV-2 Interaction"},
...
] } }

 

This response can be parsed with JSON libraries and be used in machine learning and AI tasks.

Creating an Example Dataframe with Pandas

The response from any GraphQL API call can be parsed with JSON like any other request. Data is machine learning and AI ready.

Example code that demonstrates a process for creating a dataframe from the previous response object:

import pandas as pd
import json

json_data = json.loads(response.text) #response from API call
df_data = json_data['data']['reportsets']
df = pd.DataFrame(df_data)
 
 Which results in a new dataframe for reportsets query:
 
Python_tutorial_eg_df