How to use the fastapi.APIRouter 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 httprunner / httprunner / httprunner / app / routers / debugtalk.py View on Github external
import contextlib
import sys
from io import StringIO

from fastapi import APIRouter
from loguru import logger
from starlette.requests import Request

router = APIRouter()


@contextlib.contextmanager
def stdout_io(stdout=None):
    old = sys.stdout
    if stdout is None:
        stdout = StringIO()
    sys.stdout = stdout
    yield stdout
    sys.stdout = old


@router.post("/hrun/debug/debugtalk_py", tags=["debugtalk"])
async def debug_python(request: Request):
    body = await request.body()
github msys2 / msys2-web / app / api.py View on Github external
from functools import cmp_to_key

from fastapi import FastAPI, APIRouter, Request, Response
from fastapi.responses import JSONResponse

from typing import Tuple, Dict, List, Set, Any, Iterable
from .appstate import state, SrcInfoPackage
from .utils import package_name_is_vcs, version_is_newer_than

router = APIRouter()


def cmp_(a: Any, b: Any) -> int:
    return int((a > b) - (a < b))


def cmp_func(e1: Dict, e2: Dict) -> int:
    # package with fewest deps first
    e1_k = (len(e1["makedepends"]), sorted(e1["provides"]))
    e2_k = (len(e2["makedepends"]), sorted(e2["provides"]))
    e1_p, e1_m = e1["provides"], e1["makedepends"]
    e2_p, e2_m = e2["provides"], e2["makedepends"]

    if e1_p & e2_m and e2_p & e1_m:
        # cyclic dependency!
        return cmp_(e1_k, e2_k)
github lfos / aurweb / aurweb / routers / sso.py View on Github external
import fastapi

from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import Depends, HTTPException
from fastapi.responses import RedirectResponse
from sqlalchemy.sql import select
from starlette.requests import Request

import aurweb.config
import aurweb.db

from aurweb.l10n import get_translator_for_request
from aurweb.schema import Bans, Sessions, Users

router = fastapi.APIRouter()

oauth = OAuth()
oauth.register(
    name="sso",
    server_metadata_url=aurweb.config.get("sso", "openid_configuration"),
    client_kwargs={"scope": "openid"},
    client_id=aurweb.config.get("sso", "client_id"),
    client_secret=aurweb.config.get("sso", "client_secret"),
)


@router.get("/sso/login")
async def login(request: Request, redirect: str = None):
    """
    Redirect the user to the SSO provider’s login page.
github abhinavkashyap / sciwing / sciwing / api / routers / citation_intent_clf.py View on Github external
from fastapi import APIRouter
from sciwing.models.citation_intent_clf import CitationIntentClassification

router = APIRouter()

citation_intent_clf_model = None


@router.get("/cit_int_clf/{citation}")
def classify_citation_intent(citation: str):
    """ End point to classify a citation intent into ```Background`, `Method`, `Result Comparison```

    Parameters
    ----------
    citation : str
        String containing the citation to another work

    Returns
    -------
    JSON
github 3lpsy / boucanpy / boucanpy / api / routers / http_request / router.py View on Github external
from boucanpy.core import logger, abort, only
from boucanpy.core.security import ScopedTo, TokenPayload
from boucanpy.core import SortQS, PaginationQS
from boucanpy.core.http_server import HttpServerRepo
from boucanpy.core.zone import ZoneRepo

from boucanpy.core.http_request import (
    HttpRequestRepo,
    HttpRequestsResponse,
    HttpRequestResponse,
    HttpRequestData,
    HttpRequestCreateForm,
)

router = APIRouter()
options = {"prefix": ""}


@router.get(
    "/http-request", name="http_request.index", response_model=HttpRequestsResponse
)
async def index(
    sort_qs: SortQS = Depends(SortQS),
    pagination: PaginationQS = Depends(PaginationQS),
    http_request_repo: HttpRequestRepo = Depends(HttpRequestRepo()),
    token: TokenPayload = Depends(ScopedTo("http-request:list")),
):
    pg, items = (
        http_request_repo.loads("http_server")
        .sort(sort_qs)
        .includes("http_server")
github nsidnev / fastapi-realworld-example-app / app / api / routes / articles / articles_resource.py View on Github external
from app.api.dependencies.database import get_repository
from app.db.repositories.articles import ArticlesRepository
from app.models.domain.articles import Article
from app.models.domain.users import User
from app.models.schemas.articles import (
    ArticleForResponse,
    ArticleInCreate,
    ArticleInResponse,
    ArticleInUpdate,
    ArticlesFilters,
    ListOfArticlesInResponse,
)
from app.resources import strings
from app.services.articles import check_article_exists, get_slug_for_article

router = APIRouter()


@router.get("", response_model=ListOfArticlesInResponse, name="articles:list-articles")
async def list_articles(
    articles_filters: ArticlesFilters = Depends(get_articles_filters),
    user: Optional[User] = Depends(get_current_user_authorizer(required=False)),
    articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)),
) -> ListOfArticlesInResponse:
    articles = await articles_repo.filter_articles(
        tag=articles_filters.tag,
        author=articles_filters.author,
        favorited=articles_filters.favorited,
        limit=articles_filters.limit,
        offset=articles_filters.offset,
        requested_user=user,
    )
github msys2 / msys2-web / app / web.py View on Github external
import httpx
import jinja2

from fastapi import APIRouter, Request, HTTPException, Depends, Response, FastAPI
from fastapi.templating import Jinja2Templates
from fastapi.responses import RedirectResponse, HTMLResponse, JSONResponse
from fastapi_etag import Etag
from fastapi.staticfiles import StaticFiles
from fastapi_etag import add_exception_handler as add_etag_exception_handler

from .appstate import state, get_repositories, Package, is_skipped, Source, DepType
from .utils import package_name_is_vcs, extract_upstream_version, version_is_newer_than
from .appconfig import REQUEST_TIMEOUT

router = APIRouter(default_response_class=HTMLResponse)
DIR = os.path.dirname(os.path.realpath(__file__))
templates = Jinja2Templates(directory=os.path.join(DIR, "templates"))


async def get_etag(request: Request) -> str:
    return state.etag


def template_filter(name: str) -> Callable:
    def wrap(f: Callable) -> Callable:
        templates.env.filters[name] = f
        return f
    return wrap


def context_function(name: str) -> Callable:
github nsidnev / fastapi-realworld-example-app / app / api / api_v1 / endpoints / tag.py View on Github external
from fastapi import APIRouter, Depends

from app.crud.tag import fetch_all_tags
from app.db.database import DataBase, get_database
from app.models.tag import TagsList

router = APIRouter()


@router.get("/tags", response_model=TagsList, tags=["tags"])
async def get_all_tags(db: DataBase = Depends(get_database)):
    async with db.pool.acquire() as conn:
        tags = await fetch_all_tags(conn)
        return TagsList(tags=[tag.tag for tag in tags])
github deepset-ai / haystack / rest_api / controller / search.py View on Github external
from haystack import Finder
from rest_api.config import DB_HOST, DB_PORT, DB_USER, DB_PW, DB_INDEX, ES_CONN_SCHEME, TEXT_FIELD_NAME, SEARCH_FIELD_NAME, \
    EMBEDDING_DIM, EMBEDDING_FIELD_NAME, EXCLUDE_META_DATA_FIELDS, RETRIEVER_TYPE, EMBEDDING_MODEL_PATH, USE_GPU, READER_MODEL_PATH, \
    BATCHSIZE, CONTEXT_WINDOW_SIZE, TOP_K_PER_CANDIDATE, NO_ANS_BOOST, MAX_PROCESSES, MAX_SEQ_LEN, DOC_STRIDE, \
    DEFAULT_TOP_K_READER, DEFAULT_TOP_K_RETRIEVER, CONCURRENT_REQUEST_PER_WORKER, FAQ_QUESTION_FIELD_NAME, \
    EMBEDDING_MODEL_FORMAT, READER_TYPE, READER_TOKENIZER, GPU_NUMBER
from rest_api.controller.utils import RequestLimiter
from haystack.database.elasticsearch import ElasticsearchDocumentStore
from haystack.reader.farm import FARMReader
from haystack.reader.transformers import TransformersReader
from haystack.retriever.base import BaseRetriever
from haystack.retriever.sparse import ElasticsearchRetriever, ElasticsearchFilterOnlyRetriever
from haystack.retriever.dense import EmbeddingRetriever

logger = logging.getLogger(__name__)
router = APIRouter()

# Init global components: DocumentStore, Retriever, Reader, Finder
document_store = ElasticsearchDocumentStore(
    host=DB_HOST,
    port=DB_PORT,
    username=DB_USER,
    password=DB_PW,
    index=DB_INDEX,
    scheme=ES_CONN_SCHEME,
    ca_certs=False,
    verify_certs=False,
    text_field=TEXT_FIELD_NAME,
    search_fields=SEARCH_FIELD_NAME,
    embedding_dim=EMBEDDING_DIM,
    embedding_field=EMBEDDING_FIELD_NAME,
    excluded_meta_data=EXCLUDE_META_DATA_FIELDS,  # type: ignore
github mlrun / mlrun / mlrun / api / api / endpoints / runs.py View on Github external
from distutils.util import strtobool
from http import HTTPStatus
from typing import List

from fastapi import APIRouter, Depends, Request, Query
from fastapi.concurrency import run_in_threadpool
from sqlalchemy.orm import Session

from mlrun.api.api import deps
from mlrun.api.api.utils import log_and_raise
from mlrun.api.singletons import get_db
from mlrun.utils import logger

router = APIRouter()


# curl -d @/path/to/run.json http://localhost:8080/run/p1/3?commit=yes
@router.post("/run/{project}/{uid}")
async def store_run(
        request: Request,
        project: str,
        uid: str,
        iter: int = 0,
        db_session: Session = Depends(deps.get_db_session)):
    data = None
    try:
        data = await request.json()
    except ValueError:
        log_and_raise(HTTPStatus.BAD_REQUEST, reason="bad JSON body")