@@ -15,26 +15,41 @@ class MarzbanAPI:
1515 This class provides a unified interface to all API sections through
1616 modular sub-APIs for better organization and maintainability.
1717
18- Usage:
18+ You can authenticate in two ways:
19+ 1. Using username and password (traditional method)
20+ 2. Using a pre-existing access token (direct token method)
21+
22+ Usage with username/password:
1923 async with MarzbanAPI("http://127.0.0.1:8000", "admin", "password") as api:
20- # Access different API sections
2124 users = await api.user.get_users()
2225 stats = await api.system.get_stats()
23- nodes = await api.node.get_all()
26+
27+ Usage with access token:
28+ async with MarzbanAPI("http://127.0.0.1:8000", access_token="your_jwt_token") as api:
29+ users = await api.user.get_users()
30+ stats = await api.system.get_stats()
2431 """
2532
26- def __init__ (self , base_url : str , username : str , password : str ):
33+ def __init__ (
34+ self ,
35+ base_url : str ,
36+ username : Optional [str ] = None ,
37+ password : Optional [str ] = None ,
38+ access_token : Optional [str ] = None
39+ ):
2740 """
2841 Initialize MarzbanAPI client.
2942
3043 Args:
3144 base_url: Base URL of Marzban API (e.g. http://127.0.0.1:8000)
32- username: Admin username for authentication
33- password: Admin password for authentication
45+ username: Admin username for authentication (optional if access_token provided)
46+ password: Admin password for authentication (optional if access_token provided)
47+ access_token: Pre-existing JWT token for direct authentication (optional)
3448 """
3549 self .base_url = base_url .rstrip ('/' )
3650 self .username = username
3751 self .password = password
52+ self .access_token = access_token
3853 self .token : Optional [str ] = None
3954 self .client = httpx .AsyncClient (timeout = 30.0 )
4055
@@ -56,11 +71,18 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
5671
5772 async def authenticate (self ):
5873 """Authenticate with Marzban API and initialize all sections."""
59- self .token = await get_token_from_credentials (
60- self .username ,
61- self .password ,
62- self .base_url
63- )
74+ # Use provided access token or get new token from credentials
75+ if self .access_token :
76+ self .token = self .access_token
77+ else :
78+ if not self .username or not self .password :
79+ raise ValueError ("Either access_token or both username and password must be provided" )
80+
81+ self .token = await get_token_from_credentials (
82+ self .username ,
83+ self .password ,
84+ self .base_url
85+ )
6486
6587 # Initialize all API sections with shared client and token
6688 self .user = UserAPI (self .client , self .base_url , self .token )
0 commit comments