TL;DR
--Developed a library called "apywrapper"
--API wrapper can be developed at explosive speed --Supports RESTful API __ only __
I think there are many things to think about when creating an API wrapper, such as request processing and serialization of response data, but when you really want data, thinking about them and worrying about them can be a waste of time.
_ When I throw a parameter to the server, an object is returned in the response _
In fact, that's all I want to do.
I will introduce the code that realizes it with ʻapy wrapper`
from dataclasses import dataclass
from apywrapper import Apy
api = Apy(host="https://example.com/api", headers={"api_token": "xxxxxx"})
@dataclass
class User:
user_id: str
name: str
age: int
@api.get("/users/{user_id}")
def get_user(user_id: str):
return User, {"user_id": user_id}
That's it! If you call get_user ("sh1ma ")
, you will get a user object with ʻuser_id`` sh1ma`!
from dataclasses import dataclass
from apywrapper import Apy
This line imports the body ʻApy of
data class and ʻapywrapper
api = Apy(host="https://example.com/api", headers={"api_token": "xxxxxx"})
Specify the host of the API here. headers
is optional, but in most cases you will need it. (token etc.)
@dataclass
class User:
user_id: str
name: str
age: int
Defines the class of objects required as a data class. This is used to serialize the response.
@api.get("/users/{user_id}")
def get_user(user_id: str):
return User, {"user_id": user_id}
The @ api.get ("/ users / {user_id} ")
part is very important. Here, specify the Path of the API. You can pass a variable to Path by enclosing it in curly braces like {user_id}
.
def get_user (user_id: str):
defines a function. There is nothing special about it. The argument name of the ʻuser_id` part is not actually used, so feel free to use any name you like!
return User, {"user_id ": user_id}
is very, very important! Everything is packed here! Of the values to return
, the first part of ʻUser will pass the object to be responded (even if a list (
List [User] ) is to be returned, specify a singular, that is, ʻUser
. Masu). The following {"user_id ": user_id}
part is the request parameter. ʻUser_id` is a Path variable, but you can also specify queries and json data in the same way.
It's hard to understand, so here's an example.
@api.post("/users")
def create_user(username: str, user_id: str):
return User, {"user_name": username, "user_id": user_id}
The data when POSTing is JSON, but parameters can be specified in the same way as when GET.
@api.get("/users/{user_id}")
def get_user(user_id: str, only_name: bool):
return User, {"user_id": user_id, "only_name": True}
You can specify queries and Path variables as well.
pip install apywrapper
――It is still under development. --Currently, it does not support POST or PUT query strings __ ――We are waiting for PR and issues! (https://github.com/sh1ma/apywrapper)
Recommended Posts