Python fastapi.FastAPI() Examples
The following are 30
code examples of fastapi.FastAPI().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
fastapi
, or try the search function
.
Example #1
Source File: test_profiles.py From fastapi-realworld-example-app with MIT License | 7 votes |
def test_user_that_follows_another_will_receive_profile_with_follow( app: FastAPI, authorized_client: AsyncClient, pool: Pool, test_user: UserInDB ) -> None: async with pool.acquire() as conn: users_repo = UsersRepository(conn) user = await users_repo.create_user( username="user_for_following", email="test-for-following@email.com", password="password", ) profiles_repo = ProfilesRepository(conn) await profiles_repo.add_user_into_followers( target_user=user, requested_user=test_user ) response = await authorized_client.get( app.url_path_for("profiles:get-profile", username=user.username) ) profile = ProfileInResponse(**response.json()) assert profile.profile.username == user.username assert profile.profile.following
Example #2
Source File: test_users.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_user_can_not_take_already_used_credentials( app: FastAPI, authorized_client: AsyncClient, pool: Pool, token: str, credentials_part: str, credentials_value: str, ) -> None: user_dict = { "username": "not_taken_username", "password": "password", "email": "free_email@email.com", } user_dict.update({credentials_part: credentials_value}) async with pool.acquire() as conn: users_repo = UsersRepository(conn) await users_repo.create_user(**user_dict) response = await authorized_client.put( app.url_path_for("users:update-current-user"), json={"user": {credentials_part: credentials_value}}, ) assert response.status_code == status.HTTP_400_BAD_REQUEST
Example #3
Source File: exception_handlers.py From fastapi_contrib with MIT License | 6 votes |
def setup_exception_handlers(app: FastAPI) -> None: """ Helper function to setup exception handlers for app. Use during app startup as follows: .. code-block:: python app = FastAPI() @app.on_event('startup') async def startup(): setup_exception_handlers(app) :param app: app object, instance of FastAPI :return: None """ app.add_exception_handler(StarletteHTTPException, http_exception_handler) app.add_exception_handler( RequestValidationError, validation_exception_handler ) app.add_exception_handler(404, not_found_error_handler) app.add_exception_handler(500, internal_server_error_handler)
Example #4
Source File: test_invalid_sequence_param.py From fastapi with MIT License | 6 votes |
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
Example #5
Source File: test_operations_signatures.py From fastapi with MIT License | 6 votes |
def test_signatures_consistency(): base_sig = inspect.signature(APIRouter.get) for method_name in method_names: router_method = getattr(APIRouter, method_name) app_method = getattr(FastAPI, method_name) router_sig = inspect.signature(router_method) app_sig = inspect.signature(app_method) param: inspect.Parameter for key, param in base_sig.parameters.items(): router_param: inspect.Parameter = router_sig.parameters[key] app_param: inspect.Parameter = app_sig.parameters[key] assert param.annotation == router_param.annotation assert param.annotation == app_param.annotation assert param.default == router_param.default assert param.default == app_param.default
Example #6
Source File: test_asgi.py From schemathesis with MIT License | 6 votes |
def test_wsgi_app(testdir, cli): module = testdir.make_importable_pyfile( location=""" from fastapi import FastAPI from fastapi import HTTPException app = FastAPI() @app.get("/api/success") async def success(): return {"success": True} @app.get("/api/failure") async def failure(): raise HTTPException(status_code=500) return {"failure": True} """ ) result = cli.run("/openapi.json", "--app", f"{module.purebasename}:app") assert result.exit_code == ExitCode.TESTS_FAILED, result.stdout assert "1 passed, 1 failed in" in result.stdout
Example #7
Source File: main.py From fastapi-realworld-example-app with MIT License | 6 votes |
def get_application() -> FastAPI: application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION) application.add_middleware( CORSMiddleware, allow_origins=ALLOWED_HOSTS or ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) application.add_event_handler("startup", create_start_app_handler(application)) application.add_event_handler("shutdown", create_stop_app_handler(application)) application.add_exception_handler(HTTPException, http_error_handler) application.add_exception_handler(RequestValidationError, http422_error_handler) application.include_router(api_router, prefix=API_PREFIX) return application
Example #8
Source File: test_profiles.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_user_that_does_not_follows_another_will_receive_profile_without_follow( app: FastAPI, authorized_client: AsyncClient, pool: Pool ) -> None: async with pool.acquire() as conn: users_repo = UsersRepository(conn) user = await users_repo.create_user( username="user_for_following", email="test-for-following@email.com", password="password", ) response = await authorized_client.get( app.url_path_for("profiles:get-profile", username=user.username) ) profile = ProfileInResponse(**response.json()) assert profile.profile.username == user.username assert not profile.profile.following
Example #9
Source File: test_registration.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_user_success_registration( app: FastAPI, client: AsyncClient, pool: Pool ) -> None: email, username, password = "test@test.com", "username", "password" registration_json = { "user": {"email": email, "username": username, "password": password} } response = await client.post( app.url_path_for("auth:register"), json=registration_json ) assert response.status_code == HTTP_201_CREATED async with pool.acquire() as conn: repo = UsersRepository(conn) user = await repo.get_user_by_email(email=email) assert user.email == email assert user.username == username assert user.check_password(password)
Example #10
Source File: test_registration.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_failed_user_registration_when_some_credentials_are_taken( app: FastAPI, client: AsyncClient, test_user: UserInDB, credentials_part: str, credentials_value: str, ) -> None: registration_json = { "user": { "email": "test@test.com", "username": "username", "password": "password", } } registration_json["user"][credentials_part] = credentials_value response = await client.post( app.url_path_for("auth:register"), json=registration_json ) assert response.status_code == HTTP_400_BAD_REQUEST
Example #11
Source File: test_comments.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_user_can_not_delete_not_authored_comment( app: FastAPI, authorized_client: AsyncClient, test_article: Article, pool: Pool ) -> None: async with pool.acquire() as connection: users_repo = UsersRepository(connection) user = await users_repo.create_user( username="test_author", email="author@email.com", password="password" ) comments_repo = CommentsRepository(connection) comment = await comments_repo.create_comment_for_article( body="tmp", article=test_article, user=user ) forbidden_response = await authorized_client.delete( app.url_path_for( "comments:delete-comment-from-article", slug=test_article.slug, comment_id=str(comment.id_), ) ) assert forbidden_response.status_code == status.HTTP_403_FORBIDDEN
Example #12
Source File: test_comments.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_user_can_delete_own_comment( app: FastAPI, authorized_client: AsyncClient, test_article: Article ) -> None: created_comment_response = await authorized_client.post( app.url_path_for("comments:create-comment-for-article", slug=test_article.slug), json={"comment": {"body": "comment"}}, ) created_comment = CommentInResponse(**created_comment_response.json()) await authorized_client.delete( app.url_path_for( "comments:delete-comment-from-article", slug=test_article.slug, comment_id=str(created_comment.comment.id_), ) ) comments_for_article_response = await authorized_client.get( app.url_path_for("comments:get-comments-for-article", slug=test_article.slug) ) comments = ListOfCommentsInResponse(**comments_for_article_response.json()) assert len(comments.comments) == 0
Example #13
Source File: test_comments.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_user_can_add_comment_for_article( app: FastAPI, authorized_client: AsyncClient, test_article: Article ) -> None: created_comment_response = await authorized_client.post( app.url_path_for("comments:create-comment-for-article", slug=test_article.slug), json={"comment": {"body": "comment"}}, ) created_comment = CommentInResponse(**created_comment_response.json()) comments_for_article_response = await authorized_client.get( app.url_path_for("comments:get-comments-for-article", slug=test_article.slug) ) comments = ListOfCommentsInResponse(**comments_for_article_response.json()) assert created_comment.comment == comments.comments[0]
Example #14
Source File: test_users.py From fastapi-realworld-example-app with MIT License | 6 votes |
def test_user_can_change_password( app: FastAPI, authorized_client: AsyncClient, test_user: UserInDB, token: str, pool: Pool, ) -> None: response = await authorized_client.put( app.url_path_for("users:update-current-user"), json={"user": {"password": "new_password"}}, ) assert response.status_code == status.HTTP_200_OK user_profile = UserInResponse(**response.json()) async with pool.acquire() as connection: users_repo = UsersRepository(connection) user = await users_repo.get_user_by_username( username=user_profile.user.username ) assert user.check_password("new_password")
Example #15
Source File: conftest.py From fastapi-realworld-example-app with MIT License | 5 votes |
def pool(initialized_app: FastAPI) -> Pool: return initialized_app.state.pool
Example #16
Source File: conftest.py From fastapi-realworld-example-app with MIT License | 5 votes |
def initialized_app(app: FastAPI) -> FastAPI: async with LifespanManager(app): yield app
Example #17
Source File: test_articles.py From fastapi-realworld-example-app with MIT License | 5 votes |
def test_not_existing_tags_will_be_created_without_duplication( app: FastAPI, authorized_client: AsyncClient, test_user: UserInDB ) -> None: article_data = { "title": "Test Slug", "body": "does not matter", "description": "¯\\_(ツ)_/¯", "tagList": ["tag1", "tag2", "tag3", "tag3"], } response = await authorized_client.post( app.url_path_for("articles:create-article"), json={"article": article_data} ) article = ArticleInResponse(**response.json()) assert set(article.article.tags) == {"tag1", "tag2", "tag3"}
Example #18
Source File: test_articles.py From fastapi-realworld-example-app with MIT License | 5 votes |
def test_user_can_create_article( app: FastAPI, authorized_client: AsyncClient, test_user: UserInDB ) -> None: article_data = { "title": "Test Slug", "body": "does not matter", "description": "¯\\_(ツ)_/¯", } response = await authorized_client.post( app.url_path_for("articles:create-article"), json={"article": article_data} ) article = ArticleInResponse(**response.json()) assert article.article.title == article_data["title"] assert article.article.author.username == test_user.username
Example #19
Source File: main.py From uvicorn-gunicorn-fastapi-docker with MIT License | 5 votes |
def read_root(): message = f"Hello world! From FastAPI running on Uvicorn with Gunicorn. Using Python {version}" return {"message": message}
Example #20
Source File: test_utils.py From fastapi_contrib with MIT License | 5 votes |
def test_setup_opentracing(): _app = FastAPI() setup_opentracing(_app) assert isinstance(_app.tracer, Tracer)
Example #21
Source File: test_articles.py From fastapi-realworld-example-app with MIT License | 5 votes |
def test_user_can_not_create_article_with_duplicated_slug( app: FastAPI, authorized_client: AsyncClient, test_article: Article ) -> None: article_data = { "title": "Test Slug", "body": "does not matter", "description": "¯\\_(ツ)_/¯", } response = await authorized_client.post( app.url_path_for("articles:create-article"), json={"article": article_data} ) assert response.status_code == status.HTTP_400_BAD_REQUEST
Example #22
Source File: test_authentication.py From fastapi-realworld-example-app with MIT License | 5 votes |
def test_unable_to_login_when_user_does_not_exist_any_more( app: FastAPI, client: AsyncClient, authorization_prefix: str ) -> None: token = create_access_token_for_user( User(username="user", email="email@email.com"), "secret" ) response = await client.get( app.url_path_for("users:get-current-user"), headers={"Authorization": f"{authorization_prefix} {token}"}, ) assert response.status_code == HTTP_403_FORBIDDEN
Example #23
Source File: test_authentication.py From fastapi-realworld-example-app with MIT License | 5 votes |
def test_unable_to_login_with_wrong_jwt_prefix( app: FastAPI, client: AsyncClient, token: str ) -> None: response = await client.get( app.url_path_for("users:get-current-user"), headers={"Authorization": f"WrongPrefix {token}"}, ) assert response.status_code == HTTP_403_FORBIDDEN
Example #24
Source File: utils.py From fastapi_contrib with MIT License | 5 votes |
def get_current_app() -> FastAPI: """ Retrieves FastAPI app instance from the path, specified in project's conf. :return: FastAPI app """ # TODO: cache this app = resolve_dotted_path(settings.fastapi_app) return app
Example #25
Source File: conftest.py From fastapi_login with MIT License | 5 votes |
def app(): return FastAPI()
Example #26
Source File: conftest.py From fastapi-sqlalchemy with MIT License | 5 votes |
def app(): return FastAPI()
Example #27
Source File: server.py From DeepPavlov with Apache License 2.0 | 5 votes |
def redirect_root_to_docs(fast_app: FastAPI, func_name: str, endpoint: str, method: str) -> None: """Adds api route to server that redirects user from root to docs with opened `endpoint` description.""" @fast_app.get('/', include_in_schema=False) async def redirect_to_docs() -> RedirectResponse: operation_id = generate_operation_id_for_path(name=func_name, path=endpoint, method=method) response = RedirectResponse(url=f'/docs#/default/{operation_id}') return response
Example #28
Source File: main.py From optimade-python-tools with MIT License | 5 votes |
def add_major_version_base_url(app: FastAPI): """ Add mandatory vMajor endpoints, i.e. all except versions. """ for endpoint in (info, links, references, structures, landing): app.include_router(endpoint.router, prefix=BASE_URL_PREFIXES["major"])
Example #29
Source File: main.py From optimade-python-tools with MIT License | 5 votes |
def add_optional_versioned_base_urls(app: FastAPI): """Add the following OPTIONAL prefixes/base URLs to server: ``` /vMajor.Minor /vMajor.Minor.Patch ``` """ for version in ("minor", "patch"): for endpoint in (info, links, references, structures, landing): app.include_router(endpoint.router, prefix=BASE_URL_PREFIXES[version])
Example #30
Source File: test_articles.py From fastapi-realworld-example-app with MIT License | 5 votes |
def test_user_can_update_article( app: FastAPI, authorized_client: AsyncClient, test_article: Article, update_field: str, update_value: str, extra_updates: dict, ) -> None: response = await authorized_client.put( app.url_path_for("articles:update-article", slug=test_article.slug), json={"article": {update_field: update_value}}, ) assert response.status_code == status.HTTP_200_OK article = ArticleInResponse(**response.json()).article article_as_dict = article.dict() assert article_as_dict[update_field] == update_value for extra_field, extra_value in extra_updates.items(): assert article_as_dict[extra_field] == extra_value exclude_fields = {update_field, *extra_updates.keys(), "updated_at"} assert article.dict(exclude=exclude_fields) == test_article.dict( exclude=exclude_fields )