Make simple web API with FastAPI, pycembldb and razi #chemoinformatics #RDKit #ChEMBLDB

As reader know, chembl is not only useful but also opensource database. Recently I’m playing with chembl and its python wrapper named pychembldb and cartridge named razi.

I recommend reader who is interested in the chemoinformatics to install these very useful python packages. ;)

BTW, I think it is useful if I could use these packages and chembl db in conveniently from web service. So web based API seems useful for me. I mainly use flask for to do these task. But today, I used FastAPI for test. FastAPI is new web flame work and it works faster than Flask.

The code seems almost as same as flask so learning cost is not expensive I think.

For the test, I made a simple post script which gets query substructure as a smiles and retrieve matched compound from ChEMBL27. For the substructure searching, I use rdkit postgresql cartridge via razi. I can’t find solution that how to make get url with escaped smiles string in FastAPI, so following code used post method. The code will get two parameters one is substructure and the other is limit for getting limited number of the matched compounds.

from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy.orm import create_session
from rdkit import Chem
import pychembldb

class Query(BaseModel):
    substruct: str
    limit: int

app = FastAPI()'/query/')
async def get_query(query: Query):
    sess = create_session()
    q = sess.query(pychembldb.Mols)
    q = q.filter(pychembldb.Mols.m.hassubstruct(query.substruct)).limit(query.limit)
    res = {'molregno':[], 'smi':[]}
    for row in q:
    return res

After saving the script above as, I run the serve with following command.

$ uvicorn chemblapi:app --reload

Now server will work and I can access localhost:8000/docs. The image of the page is below.

Then click post and click try it now, I can edit query of the service.

Request body is editable.

I edited request body and push execute button,. I could get response as json format. ;)

This example is not so useful for practical, but it shows that by using FastAPI I can develop useful API very conveniently.

By using pychembldb, I can get biological information with structure as a query. Wow it seems very fun!


Published by iwatobipen

I'm medicinal chemist in mid size of pharmaceutical company. I love chemoinfo, cording, organic synthesis, my family.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: