Skip to content

Requests API

David Fialho edited this page Dec 6, 2016 · 8 revisions

The requests API provides a nice and simple interface to create requests and responses. The 3 base classes are "Request", "Response", and "Connection". The exact implementation of this classes is not very important. They are meant to abstract the communication details.

Here we include a set of examples for simple usage scenarios. Some aspects of the implementation are omitted. Please refer to the code documentation for more details.

Creating a connection and making a request

For this example we use a client to make a request. However, the client can be replaced by any class implementing the 'Signer' interface.

from utils.requests.connection import connect

# We create a connection by calling the connect method and providing 
# the URL of the server that we want to connect to.
with connect(self.register_server_url) as connection:

  # Here we create an invite request
  # Note that we do not use the Join Request initializer. Instead, we
  # used the factory method 'signed()'. This allows us to abstract 
  # what parameters of the request are signed and what keys are used 
  # for signing - this might be very useful if we later want to change 
  # the signatures.
  request = JoinRequest.signed(
     joiner=client/server,
     secret_code="123456789"
  )

  # Once we have a signed request object we can make the request using the 
  # "request()" method.
  connection.request(request)
  
  # Once send a request we use the same connection to obtain the response
  # to get a response the name of the expected response should be provided
  # in this case we expect a JoinResponse.
  # Note that the argument is the class name and not an object, in other
  # words, we pass 'JoinResponse' and not 'JoinResponse()'.
  response = connection.get_response(JoinResponse)  # type: JoinResponse

  # The previous method will return JoinResponse method already initialized 
  # and ready to be used.
  # The first thing that should be done is verifying if the signatures in 
  # the response are correct for this we should use the JoinResponse's 
  # verify() method. This method has different arguments depending on the 
  # response type.
  try:
     response.verify(
        inviter=inviter_id,
        invitee=client.id,
        invitee_email=client.email,
        main_server_key=main_server_key,
        register_server_key=register_server_key
     )

  except InvalidSignature:
     # An InvalidSignature exception is raised if any of the signatures
     # in the response does not verify.
     # Here we ignore the error, however, this SHOULD NOT be ignored!!
     pass
  
  # From now on we can access the response parameters using properties
  print(response.inviter_signature)
  print(response.register_server_signature)