Metadata-Version: 2.3
Name: pyproz
Version: 0.1.0
Summary: Add your description here
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic[email]>=2.13.4
Requires-Python: >=3.12
Description-Content-Type: text/markdown

An unofficial Python SDK for accessing the ProZ.com API in a pythonic way. 

```python
import asyncio
import os

from dotenv import load_dotenv

from pyproz.client import ProzClient

load_dotenv()

CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
REDIRECT_URI = os.getenv("REDIRECT_URI")


async def main():
    client = ProzClient(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
    example_uuid = "32a9a4d0-cb6e-463f-a0ab-63d0a0418bc7"
    token = await client.oauth.get_client_credentials_token()
    user = await client.v2.users.get_by_id(token.access_token, example_uuid)
    print(user.country)  # easy access to properties


if __name__ == "__main__":
    asyncio.run(main())
```
# Overview
`pyproz` is a Python SDK for the ProZ.com API. Call a method and the request, validation and data object are generated automatically.

```python
user = await client.v2.users.get_by_id(token.access_token, user_id)
print(user.country)
```

instead of

```python
response = await requests.get(
    f"https://api.proz.com/v2/users/{user_id}",
    headers={"Authorization": f"Bearer {token}"},
)
user = response.json()
print(user["country"])
```

> **Note:** 
> This is an unofficial, community project and is not affiliated 
> with or endorsed by ProZ.com. I also noticed that some public endpoints are
> currently protected by Cloudflare. This is outside of my control and may
> affect availability.

# Installation
I recommend adding this SDK to your project with uv:
`uv add pyproz`

# Documentation
This version currently supports:
- [Authentication](https://www.proz.com/api-docs-new/#section/Authentication)
- [User service](https://www.proz.com/api-docs-new/#tag/User)

and it's intended for asynchronous use only.

## Authorization
You can use this SDK in two ways:
1. Public API as Client
2. API on behalf of a user

Both require a **Client**, which can be created [here](https://www.proz.com/oauth/client-apps).
Save `client_id`, `client_secret`, `redirect_uri` in your app's `.env` file.
These values will be loaded and passed to `ProzClient`:

```python
import asyncio
import os

from dotenv import load_dotenv

from pyproz.client import ProzClient

load_dotenv()

CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
REDIRECT_URI = os.getenv("REDIRECT_URI")


async def main():
    client = ProzClient(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
    token = await client.oauth.get_client_credentials_token()  # example usage
    print(token)
    # access_token='some_access_token' expires_in=1209600 token_type='Bearer' scope=[<Scope.PUBLIC: 'public'>] refresh_token=None


if __name__ == "__main__":
    asyncio.run(main())
```

**Available methods:**
1. `token = await client.oauth.get_client_credentials_token()`
    - returns: `Token`
    - usage: if you need a token to access the public API as a Client

2. `url = client.oauth.authorize_url()`
    - returns: `str`
    - optional args: scope: list[Scope] (see [Scope](#scope))
    - usage: first step in the OAuth2 flow (see [OAuth 2.0](#oauth-20))
    - info: generates a url with the ProZ.com login page 

3. `token = await client.oauth.exchange_code_for_token(code="some_code")`
    - returns: `Token`
    - usage: second step in the OAuth2 flow, exchanges the `code` received on your `redirect_uri` for a user token (see [OAuth 2.0](#oauth-20))

4. `token = await client.oauth.refresh_access_token(refresh_token="some_refresh_token")`
    - returns: `Token`
    - optional args: scope: list[Scope] (see [Scope](#scope))
    - usage: use when a user's `access_token` expired, to get a new one without asking them to log in again

### Token
Once you have a `Token`, you can call the API on behalf of a user by passing `token.access_token` to the `access_token` parameter of the relevant methods.
```python
class Token(BaseModel):
    access_token: str
    expires_in: int
    token_type: str
    scope: list[Scope]
    refresh_token: str | None = None
```

- `access_token` - the token used to authenticate requests
- `expires_in` - number of seconds until the token expires
- `token_type` - type of the token (e.g. `Bearer`)
- `scope` - list of `Scope` values the token was granted (see [Scope](#scope))
- `refresh_token` - present only for user tokens; use it with `refresh_access_token()` to get a new `access_token` once this one expires

### Scope
A parameter for specifying the actions you can perform on behalf of the user.

```python
class Scope(StrEnum):
    PUBLIC = "public"
    USER_EMAIL = "user.email"
    USER_NAME = "user.name"
```

- `PUBLIC` - default scope, used if none is specified
- `USER_EMAIL` - grants access to the user's email
- `USER_NAME` - grants access to the user's name

```python
from pyproz.scope import Scope

...
scope = [Scope.USER_EMAIL, Scope.USER_NAME]
url = client.oauth.authorize_url(scope=scope)
```

## OAuth 2.0
Using the API on behalf of a user requires the OAuth2 flow described below. If you are not familiar with this protocol, I recommend watching [this video](https://www.youtube.com/watch?v=U90d4mWE4Hc) first.

The flow looks like this:
1. Redirect the user to the ProZ.com login page generated by `authorize_url()`.
2. ProZ.com redirects the user back to your `redirect_uri` with a `code`
3. Exchange that `code` for a `Token` with `exchange_code_for_token()`.
4. Use `token.access_token` to call the API on behalf of the user.

Here is a minimal example using [FastAPI](https://fastapi.tiangolo.com/):

```python
from fastapi import FastAPI
from fastapi.responses import RedirectResponse

from pyproz.client import ProzClient

app = FastAPI()
client = ProzClient(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)


@app.get("/login")
async def login():
    url = client.oauth.authorize_url()
    return RedirectResponse(url)


@app.get("/callback")
async def callback(code: str):
    token = await client.oauth.exchange_code_for_token(code=code)
    user = await client.v2.user.get(token.access_token)  # returns current user
    return {"user": user.site_name}  # example: {"user": John Snow}
```

> **Note:**
> Modern OAuth 2.0 flow requires the `state` returned to your `redirect_uri` to match the one you generated in your app. 
> This protects against [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) attacks.
> It's not mentioned here, because ProZ.com's OAuth2 docs do not appear to support `state` parameter.

## User service

**Available methods:**
1. `user = await client.v2.user.get(access_token="some_token")`
    - access: private
    - returns: `User`
    - info: gets info about token owner

2. `proz_user = await client.v2.users.get_by_id(access_token="some_token", uuid="32a9a4d0-cb6e-463f-a0ab-63d0a0418bc7")`
    - access: public
    - returns: `ProzUser`
    - info: gets info about user based on his uuid

3. `proz_users = await client.v2.users.get_many(access_token="some_token", uuids=["32a9a4d0-cb6e-463f-a0ab-63d0a0418bc7"])`
    - access: public
    - returns: `list[ProzUser]`
    - info: gets info about many users based on their uuids

Returned objects (`User`, `ProzUser`) give you access to every attribute listed in the [official ProZ.com User docs](https://www.proz.com/api-docs-new/#tag/User).

## Errors
SDK can throw:
- `AuthenticationError`
- `ApiError`

Both exceptions carry the response body (parsed as JSON when possible, raw text otherwise) as their argument, so you can inspect it for details:

```python
from pyproz.errors import AuthenticationError, ApiError

try:
    user = await client.v2.users.get_by_id(
        access_token=token.access_token, uuid=example_uuid
    )
except AuthenticationError as e:
    print("Bad or expired token:", e)
except ApiError as e:
    print("Something else went wrong:", e)
```