Skip to content
This repository has been archived by the owner on Jun 14, 2024. It is now read-only.

Commit

Permalink
feat: move api v0 functionality to v1 (#168)
Browse files Browse the repository at this point in the history
# Description

Feature branch for migrating API endpoints from v0 to v1.

Refs argilla-io/argilla#4773

**Type of change**

(Please delete options that are not relevant. Remember to title the PR
according to the type of change)

- [ ] Bug fix (non-breaking change which fixes an issue)
- [x] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] Refactor (change restructuring the codebase without changing
functionality)
- [ ] Improvement (change adding some improvement to an existing
functionality)
- [ ] Documentation update

**How Has This Been Tested**

- [x] Adding new tests.

**Checklist**

- [ ] I added relevant documentation
- [ ] follows the style guidelines of this project
- [ ] I did a self-review of my code
- [ ] I made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have added tests that prove my fix is effective or that my
feature works
- [ ] I filled out [the contributor form](https://tally.so/r/n9XrxK)
(see text above)
- [ ] I have added relevant notes to the CHANGELOG.md file (See
https://keepachangelog.com/)
  • Loading branch information
jfcalvo authored May 14, 2024
1 parent 7345a7e commit e103dcd
Show file tree
Hide file tree
Showing 39 changed files with 1,909 additions and 59 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ These are the section headers that we use:

## [Unreleased]()

- Added `POST /api/v1/token` endpoint to generate a new API token for a user. ([#138](https://github.com/argilla-io/argilla-server/pull/138))
- Added `GET /api/v1/me` endpoint to get the current user information. ([#140](https://github.com/argilla-io/argilla-server/pull/140))
- Added `GET /api/v1/users` endpoint to get a list of all users. ([#142](https://github.com/argilla-io/argilla-server/pull/142))
- Added `GET /api/v1/users/:user_id` endpoint to get a specific user. ([#166](https://github.com/argilla-io/argilla-server/pull/166))
- Added `POST /api/v1/users` endpoint to create a new user. ([#146](https://github.com/argilla-io/argilla-server/pull/146))
- Added `DELETE /api/v1/users` endpoint to delete a user. ([#148](https://github.com/argilla-io/argilla-server/pull/148))
- Added `POST /api/v1/workspaces` endpoint to create a new workspace. ([#150](https://github.com/argilla-io/argilla-server/pull/150))
- Added `GET /api/v1/workspaces/:workspace_id/users` endpoint to get the users of a workspace. ([#153](https://github.com/argilla-io/argilla-server/pull/153))
- Added `POST /api/v1/workspaces/:workspace_id/users` endpoind to add a user to a workspace. ([#156](https://github.com/argilla-io/argilla-server/pull/156))
- Added `DELETE /api/v1/workspaces/:workspace_id/users/:user_id` endpoint to remove a user from a workspace. ([#158](https://github.com/argilla-io/argilla-server/pull/158))
- Added `GET /api/v1/version` endpoint to get the current Argilla version. ([#162](https://github.com/argilla-io/argilla-server/pull/162))
- Added `GET /api/v1/status` endpoint to get Argilla service status. ([#165](https://github.com/argilla-io/argilla-server/pull/165))

## [1.28.0](https://github.com/argilla-io/argilla-server/compare/v1.27.0...v1.28.0)

### Added
Expand Down
4 changes: 4 additions & 0 deletions src/argilla_server/apis/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@
users,
workspaces,
)
from argilla_server.apis.v1.handlers import authentication as authentication_v1
from argilla_server.apis.v1.handlers import (
datasets as datasets_v1,
)
from argilla_server.apis.v1.handlers import (
fields as fields_v1,
)
from argilla_server.apis.v1.handlers import info as info_v1
from argilla_server.apis.v1.handlers import (
metadata_properties as metadata_properties_v1,
)
Expand Down Expand Up @@ -113,6 +115,8 @@ def create_api_v1():
APIErrorHandler.configure_app(api_v1)

for router in [
info_v1.router,
authentication_v1.router,
datasets_v1.router,
fields_v1.router,
questions_v1.router,
Expand Down
11 changes: 6 additions & 5 deletions src/argilla_server/apis/v0/handlers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from argilla_server.contexts import accounts
from argilla_server.database import get_async_db
from argilla_server.errors import EntityAlreadyExistsError, EntityNotFoundError
from argilla_server.errors.future import NotUniqueError
from argilla_server.policies import UserPolicy, authorize
from argilla_server.pydantic_v1 import parse_obj_as
from argilla_server.schemas.v0.users import User, UserCreate
Expand Down Expand Up @@ -90,17 +91,17 @@ async def create_user(
):
await authorize(current_user, UserPolicy.create)

user = await accounts.get_user_by_username(db, user_create.username)
if user is not None:
raise EntityAlreadyExistsError(name=user_create.username, type=User)

try:
user = await accounts.create_user(db, user_create)
user = await accounts.create_user(db, user_create.dict(), user_create.workspaces)

telemetry.track_user_created(user)
except NotUniqueError:
raise EntityAlreadyExistsError(name=user_create.username, type=User)
except Exception as e:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e))

await user.awaitable_attrs.workspaces

return User.from_orm(user)


Expand Down
17 changes: 8 additions & 9 deletions src/argilla_server/apis/v0/handlers/workspaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@
from argilla_server.contexts import accounts
from argilla_server.database import get_async_db
from argilla_server.errors import EntityAlreadyExistsError, EntityNotFoundError
from argilla_server.errors.future import NotUniqueError
from argilla_server.policies import WorkspacePolicy, WorkspaceUserPolicy, authorize
from argilla_server.pydantic_v1 import parse_obj_as
from argilla_server.schemas.v0.users import User
from argilla_server.schemas.v0.workspaces import Workspace, WorkspaceCreate, WorkspaceUserCreate
from argilla_server.schemas.v0.workspaces import Workspace, WorkspaceCreate
from argilla_server.security import auth

router = APIRouter(tags=["workspaces"])
Expand All @@ -39,11 +40,11 @@ async def create_workspace(
):
await authorize(current_user, WorkspacePolicy.create)

if await accounts.get_workspace_by_name(db, workspace_create.name):
try:
workspace = await accounts.create_workspace(db, workspace_create.dict())
except NotUniqueError:
raise EntityAlreadyExistsError(name=workspace_create.name, type=Workspace)

workspace = await accounts.create_workspace(db, workspace_create)

return Workspace.from_orm(workspace)


Expand Down Expand Up @@ -84,13 +85,11 @@ async def create_workspace_user(
if not user:
raise EntityNotFoundError(name=str(user_id), type=User)

workspace_user = await accounts.get_workspace_user_by_workspace_id_and_user_id(db, workspace_id, user_id)
if workspace_user is not None:
try:
workspace_user = await accounts.create_workspace_user(db, {"workspace_id": workspace_id, "user_id": user_id})
except NotUniqueError:
raise EntityAlreadyExistsError(name=str(user_id), type=User)

workspace_user = await accounts.create_workspace_user(
db, WorkspaceUserCreate(workspace_id=workspace_id, user_id=user_id)
)
await db.refresh(user, attribute_names=["workspaces"])

return User.from_orm(workspace_user.user)
Expand Down
39 changes: 39 additions & 0 deletions src/argilla_server/apis/v1/handlers/authentication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Copyright 2021-present, the Recognai S.L. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Annotated

from fastapi import APIRouter, Depends, Form, status
from sqlalchemy.ext.asyncio import AsyncSession

from argilla_server.contexts import accounts
from argilla_server.database import get_async_db
from argilla_server.errors import UnauthorizedError
from argilla_server.schemas.v1.oauth2 import Token

router = APIRouter(tags=["Authentication"])


@router.post("/token", status_code=status.HTTP_201_CREATED, response_model=Token)
async def create_token(
*,
db: AsyncSession = Depends(get_async_db),
username: Annotated[str, Form()],
password: Annotated[str, Form()],
):
user = await accounts.authenticate_user(db, username, password)
if not user:
raise UnauthorizedError()

return Token(access_token=accounts.generate_user_token(user))
35 changes: 35 additions & 0 deletions src/argilla_server/apis/v1/handlers/info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2021-present, the Recognai S.L. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from fastapi import APIRouter, Depends

from argilla_server.contexts import info
from argilla_server.schemas.v1.info import Status, Version
from argilla_server.search_engine import SearchEngine, get_search_engine

router = APIRouter(tags=["info"])


@router.get("/version", response_model=Version)
async def get_version():
return Version(version=info.argilla_version())


@router.get("/status", response_model=Status)
async def get_status(search_engine: SearchEngine = Depends(get_search_engine)):
return Status(
version=info.argilla_version(),
search_engine=await search_engine.info(),
memory=info.memory_status(),
)
93 changes: 90 additions & 3 deletions src/argilla_server/apis/v1/handlers/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,111 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import List
from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException, Security, status
from fastapi import APIRouter, Depends, HTTPException, Request, Security, status
from sqlalchemy.ext.asyncio import AsyncSession

from argilla_server import models, telemetry
from argilla_server.contexts import accounts
from argilla_server.database import get_async_db
from argilla_server.models import User
from argilla_server.errors.future import NotUniqueError
from argilla_server.policies import UserPolicyV1, authorize
from argilla_server.schemas.v1.users import User, UserCreate, Users
from argilla_server.schemas.v1.workspaces import Workspaces
from argilla_server.security import auth

router = APIRouter(tags=["users"])


@router.get("/me", response_model=User)
async def get_current_user(request: Request, current_user: models.User = Security(auth.get_current_user)):
await telemetry.track_login(request, current_user)

return current_user


@router.get("/users/{user_id}", response_model=User)
async def get_user(
*,
db: AsyncSession = Depends(get_async_db),
user_id: UUID,
current_user: models.User = Security(auth.get_current_user),
):
await authorize(current_user, UserPolicyV1.get)

user = await accounts.get_user_by_id(db, user_id)
if user is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with id `{user_id}` not found",
)

return user


@router.get("/users", response_model=Users)
async def list_users(
*,
db: AsyncSession = Depends(get_async_db),
current_user: models.User = Security(auth.get_current_user),
):
await authorize(current_user, UserPolicyV1.list)

users = await accounts.list_users(db)

return Users(items=users)


@router.post("/users", status_code=status.HTTP_201_CREATED, response_model=User)
async def create_user(
*,
db: AsyncSession = Depends(get_async_db),
user_create: UserCreate,
current_user: models.User = Security(auth.get_current_user),
):
await authorize(current_user, UserPolicyV1.create)

try:
user = await accounts.create_user(db, user_create.dict())

telemetry.track_user_created(user)
except NotUniqueError as e:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
except Exception as e:
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e))

return user


@router.delete("/users/{user_id}", response_model=User)
async def delete_user(
*,
db: AsyncSession = Depends(get_async_db),
user_id: UUID,
current_user: models.User = Security(auth.get_current_user),
):
user = await accounts.get_user_by_id(db, user_id)
if user is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"User with id `{user_id}` not found",
)

await authorize(current_user, UserPolicyV1.delete)

await accounts.delete_user(db, user)

return user


@router.get("/users/{user_id}/workspaces", response_model=Workspaces)
async def list_user_workspaces(
*, db: AsyncSession = Depends(get_async_db), user_id: UUID, current_user: User = Security(auth.get_current_user)
*,
db: AsyncSession = Depends(get_async_db),
user_id: UUID,
current_user: models.User = Security(auth.get_current_user),
):
await authorize(current_user, UserPolicyV1.list_workspaces)

Expand Down
Loading

0 comments on commit e103dcd

Please sign in to comment.