简体   繁体   中英

How to expose spaCy as a REST API?

I am interested in using the spaCy python library for my own open source project. What I am searching for is a REST-based API. What is necessary or what is the recommended way to expose the spaCy API via a common REST interface? I already took a look into the spaCy services and the spacy-api-docker project form jgontrum . But it seems there is no offical REST API available and everyone have to do it by himself. If so, what is the best way to wrap a python spaCy method/script into a REST API? There seems to be frameworks like falcon , hug and flask to help me in doing this.

But is it the recommended approach to write my own REST API server with one of these frameworks or is there something I have overseen and spaCy is already available via a REST API interface?

spaCy is not deeply tied to any framework, so you can choose your favorite and use it. 🚀


Another option you might consider is FastAPI . For example, here's a simple spaCy entity recognition API:

from fastapi import FastAPI
from pydantic import BaseModel
import spacy

nlp_en = spacy.load("en_core_web_sm")
app = FastAPI()


class Data(BaseModel):
    text: str


@app.post("/text/")
def extract_entities(data: Data, lang: str):
    doc_en = nlp_en(data.text)
    ents = []
    for ent in doc_en.ents:
        ents.append({"text": ent.text, "label_": ent.label_})
    return {"message": data.text, "lang": lang, "ents": ents}

And the automatic docs UI looks like this:

FastAPI 文档用户界面

Disclaimers: I created FastAPI, and that's what we currently use at Explosion (the creators of spaCy). 🤷 😅

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM