Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

restkiss: Make REST simple again

restkiss: Make REST simple again

Lightning talk apresentada na Python Brasil [12], em Florianópolis/SC.

Avatar for Bruno Marques

Bruno Marques

October 18, 2016
Tweet

Other Decks in Programming

Transcript

  1. Quem? Bruno Oliveira Marques • Porto Alegre - RS •

    1ª PythonBrasil ◦ *clap, clap, clap* • Pythonista, sulista, baixista • Backend @ Crave Food Services • Mestrado em Computação @ UFRGS http://twitter.com/assinales http://twitter.com/DataMarques http://github.com/ElSaico [email protected]
  2. Abordagem tradicional (mágica) 1. Escolher framework full-stack 2. Definir schema

    no ORM 3. Definir modelo de autenticação/autorização 4. Criar classe(s) referenciando tudo isso 5. ??? 6. Profit!
  3. E se eu não quiser que o framework tome todas

    essas decisões por mim? ¯\_(ツ)_/¯
  4. Com Django class PostResource(DjangoResource): preparer = FieldsPreparer(fields={ 'id': 'id', 'title':

    'title', 'author': 'user.username', 'body': 'content', 'posted_on': 'posted_on', }) # GET /api/posts/ def list(self): return Post.objects.all() # GET /api/posts/<pk>/ def detail(self, pk): return Post.objects.get(id=pk) # POST /api/posts/ def create(self): return Post.objects.create( title=self.data['title'], content=self.data['body'] ) ... url(r'posts/$', PostResource.as_list())
  5. Sem Django! class PostResource(FlaskResource): posts = SomePostClass() preparer = FieldsPreparer(fields={

    'id': 'id', 'title': 'title', 'author': 'username', 'body': 'content', 'posted_on': 'posted_on', }) # GET /api/posts/ def list(self): return self.posts.get_all() # GET /api/posts/<pk>/ def detail(self, pk): return self.posts.get_by_id(pk) # POST /api/posts/ def create(self): return self.posts.create( title=self.data['title'], content=self.data['body'] ) ... PostResource.add_url_rules(app, rule_prefix='/posts/')
  6. Quero retornar um erro! raise Forbidden({‘message’: ‘This is dangerous knowledge

    which could kill you’}) raise NotFound({‘message’: ‘Object not found’}) raise IAmATeapot({‘short’: True, ‘stout’: True})
  7. Quero serializar de outros jeitos! class MultiSerializer(Serializer): def deserialize(self, body):

    if self.request.GET.get('fmt') == 'yaml': return yaml.safe_load(body) else: return json.load(body) def serialize(self, data): if self.request.GET.get('fmt') == 'yaml': return yaml.dump(body) else: return json.dumps(body) class PostResource(Resource): serializer = MultiSerializer