How to use the fastapi.FastAPI function in fastapi

To help you get started, we’ve selected a few fastapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tiangolo / fastapi / tests / test_invalid_sequence_param.py View on Github external
def test_invalid_dict():
    with pytest.raises(AssertionError):
        app = FastAPI()

        class Item(BaseModel):
            title: str

        @app.get("/items/")
        def read_items(q: Dict[str, Item] = Query(None)):
            pass  # pragma: no cover
github tiangolo / fastapi / tests / test_skip_defaults.py View on Github external
from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel
from starlette.testclient import TestClient

app = FastAPI()


class SubModel(BaseModel):
    a: Optional[str] = "foo"


class Model(BaseModel):
    x: Optional[int]
    sub: SubModel


class ModelSubclass(Model):
    y: int


@app.get("/", response_model=Model, response_model_exclude_unset=True)
github tiangolo / fastapi / tests / test_security_http_bearer_optional.py View on Github external
from typing import Optional

from fastapi import FastAPI, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from starlette.testclient import TestClient

app = FastAPI()

security = HTTPBearer(auto_error=False)


@app.get("/users/me")
def read_current_user(
    credentials: Optional[HTTPAuthorizationCredentials] = Security(security),
):
    if credentials is None:
        return {"msg": "Create an account first"}
    return {"scheme": credentials.scheme, "credentials": credentials.credentials}


client = TestClient(app)

openapi_schema = {
github xiaogp / recsys_faiss / faiss_model / faiss_fastapi.py View on Github external
import datetime

import faiss
from fastapi import FastAPI, Query

from utils import load_yaml_config

config = load_yaml_config("./config.yml")
faiss_model_path = config["model"]["faiss_model_path"]
index = faiss.read_index(faiss_model_path)

model_update_time = None

app = FastAPI()


@app.get("/faiss/similar_items/")
async def get_single_item_similar(
        spu_id: int = Query(
                ..., 
                title="spu_id", 
                description="item spu id", 
                gt=0), 
        n_items: int = Query(
                9, 
                titel="n_items", 
                description="topN of similar items", 
                ge=1)
        ):
    tim_str = datetime.datetime.now().strftime("%Y%m%d")
github tiangolo / fastapi / docs / tutorial / src / security / tutorial002.py View on Github external
from typing import Optional

from pydantic import BaseModel

from fastapi import Depends, FastAPI, Security
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")


class User(BaseModel):
    username: str
    email: Optional[str] = None
    full_name: Optional[str] = None
    disabled: Optional[bool] = None


def fake_decode_token(token):
    return User(
        username=token + "fakedecoded", email="john@example.com", full_name="John Doe"
    )
github tiangolo / fastapi / docs / src / query_params_str_validations / tutorial001.py View on Github external
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/")
async def read_items(q: str = None):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results
github uber / ludwig / ludwig / serve.py View on Github external
def server(model):
    app = FastAPI()

    input_features = {
        f['name'] for f in model.model_definition['input_features']
    }

    @app.get('/')
    def check_health():
        return JSONResponse({"message": "Ludwig server is up"})

    @app.post('/predict')
    async def predict(request: Request):
        form = await request.form()
        files, entry = convert_input(form)

        try:
            if (entry.keys() & input_features) != input_features:
github sumerc / yappi / performance_issue.py View on Github external
server_timing.append(f"{name}={(stats.pop().ttot * 1000):.3f}")
        if server_timing:
            response.headers["Server-Timing"] = ','.join(server_timing)
        #yappi.clear_stats()
        return response


# ######################
# ##### Usage test #####
# ######################
import asyncio

from httpx import AsyncClient
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
async def context_id_endpoint() -> Tuple[int, float]:
    start = time.time()
    await asyncio.sleep(1)
    end = time.time()
    return get_context_id(), end - start


track: Dict[str, str] = {
    "endpoint": context_id_endpoint.__qualname__,
    "pydantic": fastapi.routing.serialize_response.__qualname__,
    "render": Response.render.__qualname__,
    "dispatch": BenchMiddleware.dispatch.__qualname__
}
github tiangolo / fastapi / docs / src / query_params_str_validations / tutorial007.py View on Github external
from fastapi import FastAPI, Query

app = FastAPI()


@app.get("/items/")
async def read_items(q: str = Query(None, title="Query string", min_length=3)):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results
github tiangolo / fastapi / docs / tutorial / src / tutorial40.py View on Github external
from typing import Set

from fastapi import FastAPI
from pydantic import BaseModel
from pydantic.types import UrlStr

app = FastAPI()


class Image(BaseModel):
    url: UrlStr
    name: str


class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None
    tags: Set[str] = []
    image: Image = None