-
Notifications
You must be signed in to change notification settings - Fork 7
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
Move towards JSON API standard for responses #18
Open
ltalirz
wants to merge
3
commits into
master
Choose a base branch
from
adopt-json-api
base: master
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
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 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 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,7 @@ | ||
# -*- coding: utf-8 -*- | ||
"""pydantic models for AiiDA REST API. | ||
""" | ||
# pylint: disable=too-few-public-methods | ||
|
||
from .entities import * | ||
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. Err, I'm not really a fan of |
||
from .responses import * |
This file contains 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 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,65 @@ | ||
# -*- coding: utf-8 -*- | ||
"""Adapted JSON API models. | ||
|
||
Adapting pydantic_jsonapi.response to fit the non-compliant AiiDA REST API responses. | ||
Changes made as comments. | ||
""" | ||
# pylint: disable=missing-class-docstring,redefined-builtin,missing-function-docstring,too-few-public-methods | ||
from typing import Generic, Optional, TypeVar, get_type_hints | ||
|
||
from pydantic.generics import GenericModel | ||
from pydantic_jsonapi.filter import filter_none | ||
from pydantic_jsonapi.relationships import ResponseRelationshipsType | ||
from pydantic_jsonapi.resource_links import ResourceLinks | ||
|
||
# TypeT = TypeVar('TypeT', bound=str) | ||
# AttributesT = TypeVar("AttributesT") | ||
|
||
|
||
# class ResponseDataModel(GenericModel): | ||
|
||
# id: str | ||
# relationships: Optional[ResponseRelationshipsType] | ||
# links: Optional[ResourceLinks] | ||
|
||
# class Config: | ||
# validate_all = True | ||
# extra = "allow" # added | ||
|
||
|
||
DataT = TypeVar("DataT") # , bound=ResponseDataModel) | ||
|
||
|
||
class ResponseModel(GenericModel, Generic[DataT]): | ||
|
||
data: DataT | ||
included: Optional[list] | ||
meta: Optional[dict] | ||
links: Optional[ResourceLinks] | ||
|
||
def dict(self, *, serlialize_none: bool = False, **kwargs): | ||
response = super().dict(**kwargs) | ||
if serlialize_none: | ||
return response | ||
return filter_none(response) | ||
|
||
@classmethod | ||
def resource_object( | ||
cls, | ||
*, | ||
id: str, | ||
attributes: Optional[dict] = None, | ||
relationships: Optional[dict] = None, | ||
links: Optional[dict] = None, | ||
) -> DataT: | ||
data_type = get_type_hints(cls)["data"] | ||
if getattr(data_type, "__origin__", None) is list: | ||
data_type = data_type.__args__[0] | ||
typename = get_type_hints(data_type)["type"].__args__[0] | ||
return data_type( | ||
id=id, | ||
type=typename, | ||
attributes=attributes or {}, | ||
relationships=relationships, | ||
links=links, | ||
) |
This file contains 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,38 @@ | ||
# -*- coding: utf-8 -*- | ||
"""Response schemas for AiiDA REST API. | ||
|
||
Builds upon response schemas from `json_api` module. | ||
""" | ||
|
||
from typing import List, Type, TypeVar | ||
|
||
from pydantic_jsonapi import ErrorResponse | ||
|
||
from . import json_api | ||
from .entities import AiidaModel # pylint: disable=unused-import | ||
|
||
__all__ = ("EntityResponse", "ErrorResponse") | ||
|
||
ModelType = TypeVar("ModelType", bound="AiidaModel") | ||
|
||
|
||
def EntityResponse( | ||
# type_string: str, | ||
attributes_model: ModelType, | ||
*, | ||
use_list: bool = False, | ||
) -> Type[json_api.ResponseModel]: | ||
"""Returns entity-specif pydantic response model.""" | ||
response_data_model = attributes_model | ||
type_string = ( | ||
attributes_model._orm_entity.__name__.lower() # pylint: disable=protected-access | ||
) | ||
if use_list: | ||
response_data_model.__name__ = f"ListResponseData[{type_string}]" | ||
response_model = json_api.ResponseModel[List[response_data_model]] | ||
response_model.__name__ = f"ListResponse[{type_string}]" | ||
else: | ||
response_data_model.__name__ = f"ResponseData[{type_string}]" | ||
response_model = json_api.ResponseModel[response_data_model] | ||
response_model.__name__ = f"Response[{type_string}]" | ||
return response_model |
This file contains 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 |
---|---|---|
@@ -1,44 +1,50 @@ | ||
# -*- coding: utf-8 -*- | ||
"""Declaration of FastAPI application.""" | ||
from typing import List, Optional | ||
|
||
from aiida import orm | ||
from aiida.cmdline.utils.decorators import with_dbenv | ||
from aiida.common.exceptions import NotExistent | ||
from fastapi import APIRouter, Depends | ||
from fastapi.exceptions import HTTPException | ||
|
||
from aiida_restapi.models import User | ||
from aiida_restapi.models import EntityResponse, User | ||
|
||
from .auth import get_current_active_user | ||
|
||
__all__ = ("router",) | ||
|
||
router = APIRouter() | ||
|
||
SingleUserResponse = EntityResponse(User) | ||
ManyUserResponse = EntityResponse(User, use_list=True) | ||
|
||
|
||
@router.get("/users", response_model=List[User]) | ||
@router.get("/users", response_model=ManyUserResponse) | ||
@with_dbenv() | ||
async def read_users() -> List[User]: | ||
async def read_users() -> ManyUserResponse: | ||
"""Get list of all users""" | ||
return [User.from_orm(u) for u in orm.User.objects.find()] | ||
return ManyUserResponse(data=User.get_entities()) | ||
|
||
|
||
@router.get("/users/{user_id}", response_model=User) | ||
@router.get("/users/{user_id}", response_model=SingleUserResponse) | ||
@with_dbenv() | ||
async def read_user(user_id: int) -> Optional[User]: | ||
async def read_user(user_id: int) -> SingleUserResponse: | ||
"""Get user by id.""" | ||
orm_user = orm.User.objects.get(id=user_id) | ||
try: | ||
orm_user = orm.User.objects.get(id=user_id) | ||
except NotExistent as exc: | ||
raise HTTPException(status_code=404, detail="User not found") from exc | ||
|
||
if orm_user: | ||
return User.from_orm(orm_user) | ||
return SingleUserResponse(user=User.from_orm(orm_user)) | ||
|
||
return None | ||
|
||
|
||
@router.post("/users", response_model=User) | ||
@router.post("/users", response_model=SingleUserResponse) | ||
@with_dbenv() | ||
async def create_user( | ||
user: User, | ||
current_user: User = Depends( | ||
get_current_active_user | ||
), # pylint: disable=unused-argument | ||
) -> User: | ||
) -> SingleUserResponse: | ||
"""Create new AiiDA user.""" | ||
orm_user = orm.User(**user.dict(exclude_unset=True)).store() | ||
return User.from_orm(orm_user) | ||
return SingleUserResponse(data=User.from_orm(orm_user)) |
This file contains 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 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
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.
why pinned to a single version?