Declaring your first endpoint
Now that you have your consumer ready, you can start declaring your first endpoint.
To declare an endpoint, you need to create a method in your consumer class.
This method should be decorated with @http decorator and have a return type annotation.
Supported return types
Currently, DeclarativeX supports the following return types:
httpx.Response- if you want to have a raw response object.dict- if you want to have a dictionary object.list- if you want to have a list object.list[pydantic.BaseModel]- if you want to have a list of Pydantic model objects.list[marshmallow.Schema]- if you want to have a list of Marshmallow schema objects.list[dataclasses.Base]- if you want to have a list of dataclass objects.str- if you want to have a string object.None- if you want to have no return value.pydantic.BaseModel- if you want to have a Pydantic model object.marshmallow.Schema- if you want to have a Marshmallow schema object.dataclasses.Base- if you want to have a dataclass object.
Supported request methods
Currently, DeclarativeX supports the following request methods:
GETPOSTPUTPATCHDELETEOPTIONSHEAD
Example of declaring an endpoint
import dataclasses
from declarativex import Consumer, http
@dataclasses.dataclass
class User:
id: int
name: str
class MyConsumer(Consumer):
@http.get("/users")
def get_users(self) -> list[User]:
pass
In this example, we have a dataclass User that represents a user in our API.
We have a method get_users that is decorated with @http.get("/users"). This means that this method will call /users endpoint of our API.
The return type of this method is list[User]. This means that the response body will be parsed into a list of User objects.
Example of endpoint execution
consumer = MyConsumer.basic_sync(base_url="https://api.example.com")
users = consumer.get_users()
assert isinstance(users, list)
assert all(isinstance(user, User) for user in users)
consumer = MyConsumer.basic_async(base_url="https://api.example.com")
users = await consumer.get_users()
assert isinstance(users, list)
assert all(isinstance(user, User) for user in users)