-
Notifications
You must be signed in to change notification settings - Fork 3
feat: fastapi integration added. #137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lbukr
wants to merge
1
commit into
dapper91:dev
Choose a base branch
from
lbukr:fastapi
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import logging | ||
|
|
||
| import fastapi | ||
|
|
||
| import pjrpc.server | ||
| from pjrpc.server.integration import fastapi as integration | ||
|
|
||
| methods = pjrpc.server.MethodRegistry() | ||
|
|
||
|
|
||
| @methods.add() | ||
| async def sum(a: int, b: int) -> int: | ||
| return a + b | ||
|
|
||
|
|
||
| @methods.add() | ||
| async def sub(a: int, b: int) -> int: | ||
| return a - b | ||
|
|
||
|
|
||
| @methods.add() | ||
| async def div(a: int, b: int) -> float: | ||
| return a / b | ||
|
|
||
|
|
||
| @methods.add() | ||
| async def mult(a: int, b: int) -> int: | ||
| return a * b | ||
|
|
||
|
|
||
| @methods.add() | ||
| async def ping() -> None: | ||
| logging.info("ping") | ||
|
|
||
|
|
||
| jsonrpc_app = integration.Application('/api/v1') | ||
| jsonrpc_app.add_methods(methods) | ||
|
|
||
| app = fastapi.FastAPI() | ||
| app.mount("/rpc", jsonrpc_app.http_app) | ||
|
|
||
| if __name__ == "__main__": | ||
| logging.basicConfig(level=logging.INFO) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| import uuid | ||
| from typing import Annotated, Any, Mapping | ||
|
|
||
| import fastapi | ||
| import pydantic as pd | ||
|
|
||
| import pjrpc.server.specs.extractors.pydantic | ||
| from pjrpc.server.integration import fastapi as integration | ||
| from pjrpc.server.specs import extractors, openapi | ||
| from pjrpc.server.specs.openapi import ui | ||
| from pjrpc.server.validators import pydantic as validators | ||
|
|
||
| methods = pjrpc.server.MethodRegistry( | ||
| validator_factory=validators.PydanticValidatorFactory(exclude=integration.is_fastapi_request), | ||
| metadata_processors=[ | ||
| openapi.MethodSpecificationGenerator( | ||
| extractor=extractors.pydantic.PydanticMethodInfoExtractor( | ||
| exclude=integration.is_fastapi_request, | ||
| ), | ||
| ), | ||
| ], | ||
| ) | ||
|
|
||
| credentials = {"admin": "admin"} | ||
|
|
||
|
|
||
| UserName = Annotated[ | ||
| str, | ||
| pd.Field(description="User name", examples=["John"]), | ||
| ] | ||
|
|
||
| UserSurname = Annotated[ | ||
| str, | ||
| pd.Field(description="User surname", examples=["Doe"]), | ||
| ] | ||
|
|
||
| UserAge = Annotated[ | ||
| int, | ||
| pd.Field(description="User age", examples=[25]), | ||
| ] | ||
|
|
||
| UserId = Annotated[ | ||
| uuid.UUID, | ||
| pd.Field(description="User identifier", examples=["08b02cf9-8e07-4d06-b569-2c24309c1dc1"]), | ||
| ] | ||
|
|
||
|
|
||
| class UserIn(pd.BaseModel, title="User data"): | ||
| """ | ||
| User registration data. | ||
| """ | ||
|
|
||
| name: UserName | ||
| surname: UserSurname | ||
| age: UserAge | ||
|
|
||
|
|
||
| class UserOut(UserIn, title="User data"): | ||
| """ | ||
| Registered user data. | ||
| """ | ||
|
|
||
| id: UserId | ||
|
|
||
|
|
||
| class AlreadyExistsError(pjrpc.server.exceptions.TypedError): | ||
| """ | ||
| User already registered error. | ||
| """ | ||
|
|
||
| CODE = 2001 | ||
| MESSAGE = "user already exists" | ||
|
|
||
|
|
||
| class NotFoundError(pjrpc.server.exceptions.TypedError): | ||
| """ | ||
| User not found error. | ||
| """ | ||
|
|
||
| CODE = 2002 | ||
| MESSAGE = "user not found" | ||
|
|
||
|
|
||
| @methods.add( | ||
| pass_context='request', | ||
| metadata=[ | ||
| openapi.metadata( | ||
| summary="Creates a user", | ||
| tags=['users'], | ||
| errors=[AlreadyExistsError], | ||
| ), | ||
| ], | ||
| ) | ||
| def add_user(request: fastapi.Request[Mapping[str, Any]], user: UserIn) -> UserOut: | ||
| """ | ||
| Creates a user. | ||
|
|
||
| :param request: http request | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. http request is not passed. Let's pass it with to make the example more fulfilling: @methods.add(
pass_context=True,
metadata=[
openapi.metadata(
summary="Creates a user",
tags=['users'],
errors=[AlreadyExistsError],
),
],
)
def add_user(request: fastapi.Request[Mapping[str, Any]], user: UserIn) -> UserOut:
"""
Creates a user.
:param request: http request
:param object user: user data
:return object: registered user
:raise AlreadyExistsError: user already exists
""" |
||
| :param object user: user data | ||
| :return object: registered user | ||
| :raise AlreadyExistsError: user already exists | ||
| """ | ||
|
|
||
|
|
||
| @methods.add( | ||
| pass_context='request', | ||
| metadata=[ | ||
| openapi.metadata( | ||
| summary="Returns a user", | ||
| tags=['users'], | ||
| errors=[NotFoundError], | ||
| ), | ||
| ], | ||
| ) | ||
| def get_user(request: fastapi.Request[Mapping[str, Any]], user_id: UserId) -> UserOut: | ||
| """ | ||
| Returns a user. | ||
|
|
||
| :param request: http request | ||
| :param object user_id: user id | ||
| :return object: registered user | ||
| :raise NotFoundError: user not found | ||
| """ | ||
|
|
||
|
|
||
| @methods.add( | ||
| pass_context='request', | ||
| metadata=[ | ||
| openapi.metadata( | ||
| summary="Deletes a user", | ||
| tags=['users'], | ||
| errors=[NotFoundError], | ||
| deprecated=True, | ||
| ), | ||
| ], | ||
| ) | ||
| def delete_user(request: fastapi.Request[Mapping[str, Any]], user_id: UserId) -> None: | ||
| """ | ||
| Deletes a user. | ||
|
|
||
| :param request: http request | ||
| :param object user_id: user id | ||
| :raise NotFoundError: user not found | ||
| """ | ||
|
|
||
|
|
||
| class JSONEncoder(pjrpc.server.JSONEncoder): | ||
| def default(self, o: Any) -> Any: | ||
| if isinstance(o, pd.BaseModel): | ||
| return o.model_dump() | ||
| if isinstance(o, uuid.UUID): | ||
| return str(o) | ||
|
|
||
| return super().default(o) | ||
|
|
||
|
|
||
| openapi_spec = openapi.OpenAPI( | ||
| info=openapi.Info(version="1.0.0", title="User storage"), | ||
| ) | ||
|
|
||
| jsonrpc_app = integration.Application('/api/v1') | ||
| jsonrpc_app.add_methods(methods) | ||
|
|
||
| jsonrpc_app.add_spec(openapi_spec, path='openapi.json') | ||
| jsonrpc_app.add_spec_ui('swagger', ui.SwaggerUI(), spec_url='../openapi.json') | ||
| jsonrpc_app.add_spec_ui('redoc', ui.ReDoc(), spec_url='../openapi.json') | ||
|
|
||
|
|
||
| app = fastapi.FastAPI() | ||
| app.mount("/rpc", jsonrpc_app.http_app) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it worth to define a fastapi app variable like:
to be able to start it with
fastapi devorfastapi runcommand.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A more useful example is
The same example is described in openapi + fastapi docs