为restapi创建libs的免费方法
rest-api-lib-creator的Python项目详细描述
rest api库创建者
rest api lib creator是为restfulapi(特别是使用Django REST framework创建的那些api)创建lib的一种无样板文件的方法,但肯定适用于其他框架。
注释:
- 这是我为自己做的一个私人项目的港口。它可能解决你的需求,也可能解决不了我的需求。
- 这还是阿尔法。我在GH上打开这个只是为了看看这是不是我应该改进的。
安装:
pip install rest-api-lib-creator
示例:
- 创建自己库的最小值:
fromrest_api_lib_creator.coreimportViewsetRestApiLibclassUser(ViewsetRestApiLib):base_api_url='http://super.cool/api/users'
- 有了它,您可以随意使用您的api:
users=User.list()# Triggers a requests.get with url=http://super.cool/api/usersisinstance(users[0],User)user=User.create(first_name='Filipe',last_name='Waitman',email='filwaitman@gmail.com',photo=open('image.png','rb'))# Triggers a requests.post with url=http://super.cool/api/users and data={'first_name': 'Filipe', 'last_name': 'Waitman', 'email': 'filwaitman@gmail.com'} and files={'photo': <file binary content>}# Similarly to the call above you could create an empty object and save it:user=User()user.first_name='Filipe'user.last_name='Waitman'user.email='filwaitman@gmail.com'user.photo=open('image.png','rb')user.save()# Triggers a requests.post with url=http://super.cool/api/users and data={'first_name': 'Filipe', 'last_name': 'Waitman', 'email': 'filwaitman@gmail.com'} and files={'photo': <file binary content>}isinstance(user,User)print(user.id)# Prints the user id (assuming the API returned this field)print(user.first_name)# )rints the user first name (assuming the API returned this field)user.first_name='New name'user.save()# Triggers a requests.patch with url=http://super.cool/api/users/<user-id> and data={'first_name': 'New name'}user.delete()# Triggers a requests.delete with url=http://super.cool/api/users/<user-id>
- 如果资源返回其他嵌套资源,则也可以对它们进行分析:
classPet(ViewsetRestApiLib):base_api_url='http://super.cool/api/pets'nested_objects={'owner':User,}pet=Pet.retrieve('pet-id')isinstance(pet,Pet)isinstance(pet.owner,User)
你可以看到所有可能的定制here(总有一天我会改进这个文档)。
特别感谢:
- Django REST framework-说真的,你是最好的。
- Stripe-python lib-我以此为灵感来创建这个项目。