Repository: HTTP-APIs/hydrus
Pull request #266 (2018-08-11 06:31:21)

Sync with Develop


Patch:
diff --git a/README.md b/README.md
index 530957c..3772fa1 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
-Hydrus
+hydrus
 ===================
-Hydrus is a set of **Python** based tools for easier and efficient creation of Hypermedia driven REST-APIs. Hydrus utilises the power of [Linked Data](https://en.wikipedia.org/wiki/Linked_data) to create a powerful REST APIs to serve data.
-Hydrus uses the [Hydra(W3C)](http://www.hydra-cg.com/) standard for creation and documentation of it's APIs.
+hydrus is a set of **Python** based tools for easier and efficient creation of Hypermedia driven REST-APIs. hydrus utilises the power of [Linked Data](https://en.wikipedia.org/wiki/Linked_data) to create a powerful REST APIs to serve data.
+hydrus uses the [Hydra(W3C)](http://www.hydra-cg.com/) standard for creation and documentation of it's APIs.
 
 Table of contents
 -------------
@@ -13,7 +13,7 @@ Table of contents
 <a name="features"></a>
 Features
 -------------
-Hydrus supports the following features:
+hydrus supports the following features:
 - A client that can understand Hydra vocabulary and interacts with a Hydra supporting server to basic [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) operations on data.
 - A generic server that can serve required data and metadata(in the form of API documentation) to a client over HTTP.
 - A middleware that allows users to use the client to interact with the server using Natural Language which is processed machine consumable language. **(under development)**
@@ -27,16 +27,16 @@ The system is built over the following standards and tools:
 - [Hydra](http://www.hydra-cg.com/) as the API standard.
 - [SQLAlchemy](http://www.sqlalchemy.org/) as the backend database connector for storage and related operations.
 
-Apart from this, there are also various Python packages that Hydrus uses. Using `python setup.py install` installs all the required dependencies.
+Apart from this, there are also various Python packages that hydrus uses. Using `python setup.py install` installs all the required dependencies.
 
 **NOTE:** You'll need to use `python3` not `python2`.
 
 <a name="demo"></a>
 Demo
 -------------
-To run a demo for Hydrus using the sample API, just do the following:
+To run a demo for hydrus using the sample API, just do the following:
 
-Clone Hydrus:
+Clone hydrus:
 ```bash
 git clone https://github.com/HTTP-APIs/hydrus
 ```
diff --git a/cli.py b/cli.py
index ff1fb4b..5c15d90 100644
--- a/cli.py
+++ b/cli.py
@@ -8,10 +8,13 @@ from hydrus.data import doc_parse
 from hydrus.hydraspec import doc_maker
 from hydrus.data.db_models import Base
 from hydrus.data.user import add_user
-from gevent.wsgi import WSGIServer
+from gevent.pywsgi import WSGIServer
+from hydrus.parser.openapi_parser import parse
+from hydrus.samples.hydra_doc_sample import doc as api_document
 from typing import Tuple
 import json
 import click
+import yaml
 
 
 @click.command()
@@ -32,13 +35,17 @@ import click
               help="Toggle token based user authentication.")
 @click.option("--serverurl", default="http://localhost",
               help="Set server url", type=str)
+
+@click.option("--openapi","-o" ,default="./petstore_openapi.yaml",type=click.File('r'),help="Location to Open API doc")
+
 @click.argument("serve", required=True)
 def startserver(adduser: Tuple, api: str, auth: bool, dburl: str,
                 hydradoc: str, port: int, serverurl: str, token: bool,
-                serve: None) -> None:
+                serve: None,openapi: str) -> None:
     """
     Python Hydrus CLI
 
+    :param openapi:                     : Sets the link to the Open Api Doc file.
     :param adduser <tuple>  : Contains the user credentials.
     :param api <str>                    : Sets the API name for the server.
     :param auth <bool>                  : Toggles the authentication.
@@ -56,6 +63,17 @@ def startserver(adduser: Tuple, api: str, auth: bool, dburl: str,
     # DB_URL = 'sqlite:///database.db'
     DB_URL = dburl
 
+    if openapi.name != './petstore_openapi.yaml':
+        with open(openapi.name, 'r') as stream:
+            try:
+                openapi_doc = yaml.load(stream)
+            except yaml.YAMLError as exc:
+                print(exc)
+        api_doc = parse(openapi_doc)
+
+        f = open("./hydrus/samples/hydra_doc_sample.py", "w")
+        f.write(api_doc)
+        f.close()
     # Define the server URL, this is what will be displayed on the Doc
     HYDRUS_SERVER_URL = "{}:{}/".format(serverurl, str(port))
 
@@ -74,8 +92,12 @@ def startserver(adduser: Tuple, api: str, auth: bool, dburl: str,
     # NOTE: You can use your own API Documentation and create a HydraDoc object using doc_maker
     #       Or you may create your own HydraDoc Documentation using doc_writer [see hydrus/hydraspec/doc_writer_sample]
     click.echo("Creating the API Documentation")
-    apidoc = doc_maker.create_doc(json.loads(hydradoc.read()),
-                                  HYDRUS_SERVER_URL, API_NAME)
+    if openapi.name != './petstore_openapi.yaml':
+        apidoc = doc_maker.create_doc(api_document, HYDRUS_SERVER_URL, API_NAME)
+    else:
+        apidoc = doc_maker.create_doc(json.loads(hydradoc.read()),
+                                      HYDRUS_SERVER_URL, API_NAME)
+
 
     # Start a session with the DB and create all classes needed by the APIDoc
     session = scoped_session(sessionmaker(bind=engine))
diff --git a/hydrus/app.py b/hydrus/app.py
index 55dce86..246b4a5 100644
--- a/hydrus/app.py
+++ b/hydrus/app.py
@@ -44,7 +44,6 @@ from hydrus.utils import get_session, get_doc, get_api_name, get_hydrus_server_u
 from flask.wrappers import Response
 from typing import Dict, List, Any, Union, Optional
 
-
 def validObject(object_: Dict[str, Any]) -> bool:
     """
         Check if the Dict passed in POST is of valid format or not.
@@ -236,13 +235,14 @@ class Entrypoint(Resource):
 class Item(Resource):
     """Handles all operations(GET, POST, PATCH, DELETE) on Items (item can be anything depending upon the vocabulary)."""
 
-    def get(self, id_: int, path: str) -> Response:
+    def get(self, id_: str, path: str) -> Response:
         """
         GET object with id = id_ from the database.
 
         :param id : Item ID
         :param path : Path for Item ( Specified in APIDoc @id)
         """
+        id_ = str(id_)
         auth_response = check_authentication_response()
         if isinstance(auth_response, Response):
             return auth_response
@@ -268,12 +268,13 @@ class Item(Resource):
                     jsonify(message), status_code=status_code)
         abort(405)
 
-    def post(self, id_: int, path: str) -> Response:
+    def post(self, id_: str, path: str) -> Response:
         """Update object of type<path> at ID<id_> with new object_ using HTTP POST.
 
         :param id_ - ID of Item to be updated
         :param path - Path for Item type( Specified in APIDoc @id)
         """
+        id_ = str(id_)
         auth_response = check_authentication_response()
         if isinstance(auth_response, Response):
             return auth_response
@@ -314,12 +315,13 @@ class Item(Resource):
 
         abort(405)
 
-    def put(self, id_: int, path: str) -> Response:
+    def put(self, id_: str, path: str) -> Response:
         """Add new object_ optional <id_> parameter using HTTP PUT.
 
         :param id_ - ID of Item to be updated
         :param path - Path for Item type( Specified in APIDoc @id) to be updated
         """
+        id_ = str(id_)
         auth_response = check_authentication_response()
         if isinstance(auth_response, Response):
             return auth_response
@@ -353,8 +355,9 @@ class Item(Resource):
 
         abort(405)
 
-    def delete(self, id_: int, path: str) -> Response:
+    def delete(self, id_: str, path: str) -> Response:
         """Delete object with id=id_ from database."""
+        id_ = str(id_)
         auth_response = check_authentication_response()
         if isinstance(auth_response, Response):
             return auth_response
@@ -678,6 +681,8 @@ class Contexts(Resource):
 
 def app_factory(API_NAME: str="api") -> Flask:
     """Create an app object."""
+
+
     app = Flask(__name__)
     app.config['SECRET_KEY'] = 'secret key'
     CORS(app)
@@ -693,7 +698,7 @@ def app_factory(API_NAME: str="api") -> Flask:
     api.add_resource(ItemCollection, "/" + API_NAME +
                      "/<string:path>", endpoint="item_collection")
     api.add_resource(Item, "/" + API_NAME +
-                     "/<string:path>/<int:id_>", endpoint="item")
+                     "/<string:path>/<uuid:id_>", endpoint="item")
     api.add_resource(Items, "/" + API_NAME +
                      "/<string:path>/add/<int_list>", "/" + API_NAME +
                      "/<string:path>/add", "/" + API_NAME +
diff --git a/hydrus/data/crud.py b/hydrus/data/crud.py
index f71f425..fbe3654 100644
--- a/hydrus/data/crud.py
+++ b/hydrus/data/crud.py
@@ -52,7 +52,7 @@ triples = with_polymorphic(Graph, '*')
 properties = with_polymorphic(BaseProperty, "*")
 
 
-def get(id_: int, type_: str, api_name: str, session: scoped_session,
+def get(id_: str, type_: str, api_name: str, session: scoped_session,
         recursive: bool = False, path: str=None) -> Dict[str, str]:
     """Retrieve an Instance with given ID from the database [GET].
     :param id_: id of object to be fetched
@@ -130,7 +130,7 @@ def get(id_: int, type_: str, api_name: str, session: scoped_session,
 
 
 def insert(object_: Dict[str, Any], session: scoped_session,
-           id_: Optional[int] =None) -> int:
+           id_: Optional[str] =None) -> str:
     """Insert an object to database [POST] and returns the inserted object.
     :param object_: object to be inserted
     :param session: sqlalchemy scoped session
@@ -344,7 +344,7 @@ def insert_multiple(objects_: List[Dict[str,
 
 
 
-def delete(id_: int, type_: str, session: scoped_session) -> None:
+def delete(id_: str, type_: str, session: scoped_session) -> None:
     """Delete an Instance and all its relations from DB given id [DELETE].
     :param id_: id of object to be deleted
     :param type_: type of object to be deleted
@@ -446,13 +446,13 @@ def delete_multiple(
     session.commit()
 
 
-def update(id_: int,
+def update(id_: str,
            type_: str,
            object_: Dict[str,
                          str],
            session: scoped_session,
            api_name: str,
-           path: str=None) -> int:
+           path: str=None) -> str:
     """Update an object properties based on the given object [PUT].
     :param id_: if of object to be updated
     :param type_: type of object to be updated
diff --git a/hydrus/data/db_models.py b/hydrus/data/db_models.py
index a461ee4..c341e8f 100644
--- a/hydrus/data/db_models.py
+++ b/hydrus/data/db_models.py
@@ -4,6 +4,7 @@ from sqlalchemy import create_engine, ForeignKey
 from sqlalchemy.ext.declarative import declarative_base
 from sqlalchemy import Column, Integer, String, DateTime
 from typing import Any
+import uuid
 # from hydrus.settings import DB_URL
 
 engine = create_engine('sqlite:///database.db')
@@ -18,7 +19,12 @@ class RDFClass(Base):
 
     __tablename__ = "classes"
 
-    id = Column(Integer, primary_key=True)
+    id = Column(
+        String,
+        default=lambda: str(
+            uuid.uuid4()),
+        unique=True,
+        primary_key=True)
     name = Column(String, unique=True)
 
     def __repr__(self) -> str:
@@ -33,8 +39,13 @@ class Instance(Base):
 
     __tablename__ = "instances"
 
-    id = Column(Integer, primary_key=True)
-    type_ = Column(Integer, ForeignKey("classes.id"), nullable=True)
+    id = Column(
+        String,
+        default=lambda: str(
+            uuid.uuid4()),
+        unique=True,
+        primary_key=True)
+    type_ = Column(String, ForeignKey("classes.id"), nullable=True)
 
 
 class BaseProperty(Base):
@@ -42,7 +53,12 @@ class BaseProperty(Base):
 
     __tablename__ = "property"
 
-    id = Column(Integer, primary_key=True)
+    id = Column(
+        String,
+        default=lambda: str(
+            uuid.uuid4()),
+        unique=True,
+        primary_key=True)
     name = Column(String, unique=True, nullable=False)
     type_ = Column(String)
 
@@ -65,7 +81,8 @@ class InstanceProperty(BaseProperty):
 
     def __repr__(self) -> str:
         """Verbose object name."""
-        return "<id='%s', name='%s', type='%s'>" % (self.id, self.name, self.type_)
+        return "<id='%s', name='%s', type='%s'>" % (
+            self.id, self.name, self.type_)
 
 
 class AbstractProperty(BaseProperty):
@@ -83,7 +100,8 @@ class AbstractProperty(BaseProperty):
 
     def __repr__(self) -> str:
         """Verbose object name."""
-        return "<id='%s', name='%s', type='%s'>" % (self.id, self.name, self.type_)
+        return "<id='%s', name='%s', type='%s'>" % (
+            self.id, self.name, self.type_)
 
 
 class Terminal(Base):
@@ -96,13 +114,19 @@ class Terminal(Base):
 
     __tablename__ = "terminals"
 
-    id = Column(Integer, primary_key=True)
+    id = Column(
+        String,
+        default=lambda: str(
+            uuid.uuid4()),
+        unique=True,
+        primary_key=True)
     value = Column(String)
     unit = Column(String)
 
     def __repr__(self) -> str:
         """Verbose object name."""
-        return "<id='%s', value='%s', unit='%s'>" % (self.id, self.value, self.unit)
+        return "<id='%s', value='%s', unit='%s'>" % (
+            self.id, self.value, self.unit)
 
 
 class Graph(Base):
@@ -110,7 +134,12 @@ class Graph(Base):
 
     __tablename__ = "graph"
 
-    id = Column(Integer, primary_key=True)
+    id = Column(
+        String,
+        default=lambda: str(
+            uuid.uuid4()),
+        unique=True,
+        primary_key=True)
     type = Column(String)
 
     __mapper_args__ = {
@@ -123,10 +152,10 @@ class GraphCAC(Graph):
     """Graph model for Class >> AbstractProperty >> Class."""
 
     __tablename__ = 'graphcac'
-    id = Column(Integer, ForeignKey('graph.id'), primary_key=True)
-    subject = Column(Integer, ForeignKey("classes.id"))
-    predicate = Column(Integer, ForeignKey("property.id"))
-    object_ = Column(Integer, ForeignKey("classes.id"))
+    id = Column(String, ForeignKey('graph.id'), primary_key=True)
+    subject = Column(String, ForeignKey("classes.id"))
+    predicate = Column(String, ForeignKey("property.id"))
+    object_ = Column(String, ForeignKey("classes.id"))
 
     __mapper_args__ = {
         'polymorphic_identity': 'graphcac',
@@ -134,17 +163,19 @@ class GraphCAC(Graph):
 
     def __repr__(self) -> str:
         """Verbose object name."""
-        return "<subject='%s', predicate='%s', object_='%s'>" % (self.subject, self.predicate, self.object_)
+        return "<subject='%s', predicate='%s', object_='%s'>" % (
+            self.subject, self.predicate, self.object_)
 
 
 class GraphIAC(Graph):
     """Graph model for Instance >> AbstractProperty >> Class."""
 
     __tablename__ = 'graphiac'
-    id = Column(Integer, ForeignKey('graph.id'), primary_key=True)
-    subject = Column(Integer, ForeignKey("instances.id"))
-    predicate = Column(Integer, ForeignKey("property.id"))
-    object_ = Column(Integer, ForeignKey("classes.id"))
+    id = Column(String, ForeignKey('graph.id'), primary_key=True,default=lambda: str(
+            uuid.uuid4()))
+    subject = Column(String, ForeignKey("instances.id"))
+    predicate = Column(String, ForeignKey("property.id"))
+    object_ = Column(String, ForeignKey("classes.id"))
 
     __mapper_args__ = {
         'polymorphic_identity': 'graphiac',
@@ -152,17 +183,19 @@ class GraphIAC(Graph):
 
     def __repr__(self) -> str:
         """Verbose object name."""
-        return "<subject='%s', predicate='%s', object_='%s'>" % (self.subject, self.predicate, self.object_)
+        return "<subject='%s', predicate='%s', object_='%s'>" % (
+            self.subject, self.predicate, self.object_)
 
 
 class GraphIII(Graph):
     """Graph model for Instance >> InstanceProperty >> Instance."""
 
     __tablename__ = 'graphiii'
-    id = Column(Integer, ForeignKey('graph.id'), primary_key=True)
-    subject = Column(Integer, ForeignKey("instances.id"))
-    predicate = Column(Integer, ForeignKey("property.id"))
-    object_ = Column(Integer, ForeignKey("instances.id"))
+    id = Column(String, ForeignKey('graph.id'), primary_key=True,default=lambda: str(
+            uuid.uuid4()))
+    subject = Column(String, ForeignKey("instances.id"))
+    predicate = Column(String, ForeignKey("property.id"))
+    object_ = Column(String, ForeignKey("instances.id"))
 
     __mapper_args__ = {
         'polymorphic_identity': 'graphiii',
@@ -170,17 +203,19 @@ class GraphIII(Graph):
 
     def __repr__(self) -> str:
         """Verbose object name."""
-        return "<subject='%s', predicate='%s', object_='%s'>" % (self.subject, self.predicate, self.object_)
+        return "<subject='%s', predicate='%s', object_='%s'>" % (
+            self.subject, self.predicate, self.object_)
 
 
 class GraphIIT(Graph):
     """Graph model for Instance >> InstanceProperty >> Terminal."""
 
     __tablename__ = 'graphiit'
-    id = Column(Integer, ForeignKey('graph.id'), primary_key=True)
-    subject = Column(Integer, ForeignKey("instances.id"))
-    predicate = Column(Integer, ForeignKey("property.id"))
-    object_ = Column(Integer, ForeignKey("terminals.id"))
+    id = Column(String, ForeignKey('graph.id'), primary_key=True,default=lambda: str(
+            uuid.uuid4()))
+    subject = Column(String, ForeignKey("instances.id"))
+    predicate = Column(String, ForeignKey("property.id"))
+    object_ = Column(String, ForeignKey("terminals.id"))
 
     __mapper_args__ = {
         'polymorphic_identity': 'graphiit',
@@ -188,7 +223,8 @@ class GraphIIT(Graph):
 
     def __repr__(self) -> str:
         """Verbose object name."""
-        return "<subject='%s', predicate='%s', object_='%s'>" % (self.subject, self.predicate, self.object_)
+        return "<subject='%s', predicate='%s', object_='%s'>" % (
+            self.subject, self.predicate, self.object_)
 
 
 class User(Base):
diff --git a/hydrus/data/exceptions.py b/hydrus/data/exceptions.py
index 0e94bd9..7d6f7a6 100644
--- a/hydrus/data/exceptions.py
+++ b/hydrus/data/exceptions.py
@@ -17,7 +17,7 @@ class ClassNotFound(Exception):
 class InstanceNotFound(Exception):
     """Error when the Instance is not found."""
 
-    def __init__(self, type_: str, id_: Union[int, None] =None) -> None:
+    def __init__(self, type_: str, id_: Union[str, None] =None) -> None:
         """Constructor."""
         self.type_ = type_
         self.id_ = id_
@@ -45,7 +45,7 @@ class PropertyNotFound(Exception):
 class InstanceExists(Exception):
     """Error when the Instance already exists."""
 
-    def __init__(self, type_: str, id_: Union[int, None]=None) -> None:
+    def __init__(self, type_: str, id_: Union[str, None]=None) -> None:
         """Constructor."""
         self.type_ = type_
         self.id_ = id_
diff --git a/hydrus/parser/openapi_parser.py b/hydrus/parser/openapi_parser.py
index 3c34927..9914c88 100644
--- a/hydrus/parser/openapi_parser.py
+++ b/hydrus/parser/openapi_parser.py
@@ -6,6 +6,7 @@ import yaml
 import json
 from typing import Any, Dict, Match, Optional, Tuple, Union, List, Set
 from hydrus.hydraspec.doc_writer import HydraDoc, HydraClass, HydraClassProp, HydraClassOp
+import sys
 
 
 def try_catch_replacement(block: Any, get_this: str, default: Any) -> str:
@@ -43,17 +44,13 @@ def generate_empty_object() -> Dict[str, Any]:
         "prop_definition": list(),
         "op_definition": list(),
         "collection": False,
-        "path": ""
+        "path": "",
+        "methods": set()
     }
     return object
 
 
-def check_collection(class_name: str,
-                     global_: Dict[str,
-                                   Any],
-                     schema_obj: Dict[str, Any],
-                     method: str)->Dict[str,
-                                        Any]:
+def check_collection(schema_obj: Dict[str, Any],method: str)->bool:
     """
     Checks if the method is collection or not , checks if the method is valid
     :param class_name: name of class being parsed
@@ -77,23 +74,7 @@ def check_collection(class_name: str,
     # checks if the method is something like 'pet/{petid}'
     if valid_endpoint(method) == "collection" and collection == False:
         collection = True
-    object_ = generate_empty_object()
-    # checks if the method is supported by parser at the moment or not
-    # TODO see if it is required
-    flag = check_array_param(global_["doc"]["paths"][method])
-
-    if valid_endpoint(method) != "False":
-        try:
-            # if the class has already been parsed we will update the
-            # collection var
-            if not global_[class_name]["collection"]:
-                global_[class_name]["collection"] = True
-        except KeyError:
-            # if the class has not been parsed we will insert the object
-            object_["class_name"] = class_name
-            object_["collection"] = collection
-            global_[class_name] = object_
-    return object_
+    return collection
 
 
 def check_array_param(paths_: Dict[str, Any]) -> bool:
@@ -192,8 +173,8 @@ def get_class_details(global_: Dict[str,
 
     class_name = class_name
     # we simply check if the class has been defined or not
-    if class_name not in global_["class_names"]:
 
+    if not hasattr(global_[class_name]["class_definition"], 'endpoint'):
         desc = data
         try:
             classDefinition = HydraClass(
@@ -205,30 +186,89 @@ def get_class_details(global_: Dict[str,
         except KeyError:
             classDefinition = HydraClass(
                 class_name, class_name, class_name, endpoint=True, path=path)
+        # we need to add object to global before we can attach props
+        added = generateOrUpdateClass(class_name, False, global_, "")
+        if added:
+            global_[class_name]["class_definition"] = classDefinition
 
         properties = data["properties"]
         try:
             required = data["required"]
         except KeyError:
             required = set()
+
         for prop in properties:
-            # todo parse one more level to check 'type' and define class if needed
-            # check required from required list and add when true
+            vocabFlag = True
+            errFlag = False
+            if prop not in global_["class_names"]:
+                try:
+                    ref = properties[prop]["$ref"].split('/')
+
+                    if ref[0] == "#":
+                        get_class_details(
+                            global_,
+                            get_data_at_location(
+                                ref,
+                                global_["doc"]),
+                            get_class_name(ref),
+                            get_class_name(ref))
+                    else:
+                        vocabFlag = False
+                except KeyError:
+                    # throw exception
+                    # ERROR
+                    errFlag = True
+                    pass
+                except AttributeError:
+                    # ERROR thow
+                    pass
             flag = False
             if prop in required and len(required) > 0:
                 flag = True
-            # TODO copy stuff from semantic ref branch regarding prop exists in
-            # definitionset or not
-            global_[class_name]["prop_definition"].append(HydraClassProp(
-                "vocab:" + prop, prop, required=flag, read=True, write=True))
+            if vocabFlag:
+                if errFlag:
+                    global_[class_name]["prop_definition"].append(HydraClassProp(
+                        "", prop, required=flag, read=True, write=True))
+                else:
+                    global_[class_name]["prop_definition"].append(HydraClassProp(
+                        "vocab:" + prop, prop, required=flag, read=True, write=True))
+            else:
+                global_[class_name]["prop_definition"].append(HydraClassProp(
+                    prop, prop, required=flag, read=True, write=True))
         global_[class_name]["path"] = path
         global_[class_name]["class_definition"] = classDefinition
         global_["class_names"].add(class_name)
 
 
+def generateOrUpdateClass(name, collection, global_, path)->bool:
+    """
+    Generates or Updates the class if it already exists
+    :param name: class name
+    :param collection: if the class is collection or not
+    :param global_: global state
+    :param path: path
+    :return: bool showing if the operation was successful 
+    """
+    if valid_endpoint(path):
+        if name in global_["class_names"] and collection is True:
+            global_[name]["collection"] = True
+            return True
+        elif name in global_["class_names"] and collection is False:
+            return True
+        else:
+            object_ = generate_empty_object()
+            object_["class_name"] = name
+            object_["collection"] = collection
+            global_[name] = object_
+            global_["class_names"].add(name)
+            return True
+    else:
+        return False
+
+
 def check_for_ref(global_: Dict[str, Any],
                   path: str,
-                  block: Dict[str,Any])->str:
+                  block: Dict[str, Any])->str:
     """
     Checks for references in responses and parameters key , and adds classes to state
     :param global_: global state
@@ -236,25 +276,26 @@ def check_for_ref(global_: Dict[str, Any],
     :param block: block containing specific part of doc
     :return: class name
     """
+
     # will check if there is an external ref , go to that location , add the class in globals , will also verify
     # if we can parse this method or not , if all good will return class name
     for obj in block["responses"]:
         try:
             try:
+                # can only be internal
                 class_location = block["responses"][obj]["schema"]["$ref"].split(
                     '/')
             except KeyError:
                 class_location = block["responses"][obj]["schema"]["items"]["$ref"].split(
                     '/')
-            object_ = check_collection(
-                class_name=class_location[2],
-                global_=global_,
+            collection = check_collection(
                 schema_obj=block["responses"][obj]["schema"],
                 method=path)
+            success = generateOrUpdateClass(
+                get_class_name(class_location), collection, global_, path)
+            if not success:
+                return ""
 
-            if object_["class_name"] == "":
-                # cannot parse because method not supported
-                return object_["class_name"]
             get_class_details(
                 global_,
                 get_data_at_location(
@@ -267,29 +308,33 @@ def check_for_ref(global_: Dict[str, Any],
             pass
 
     # when we would be able to take arrays as parameters we will use
-    # check_if_collection here as well c
-    for obj in block["parameters"]:
-        try:
+    # check_if_collection here as well
+    flag = try_catch_replacement(block, "parameters", "False")
+    if flag != "False":
+        for obj in block["parameters"]:
             try:
-                class_location = obj["schema"]["$ref"].split('/')
+                try:
+                    class_location = obj["schema"]["$ref"].split('/')
+                except KeyError:
+                    class_location = obj["schema"]["items"]["$ref"].split('/')
+                collection_ = check_collection(obj["schema"], path)
+                success = generateOrUpdateClass(
+                    get_class_name(class_location), collection_, global_, path)
+                if not success:
+                    return ""
+                get_class_details(
+                    global_,
+                    get_data_at_location(
+                        class_location,
+                        global_["doc"]),
+                    get_class_name(class_location),
+                    path=path)
+                return class_location[2]
             except KeyError:
-                class_location = obj["schema"]["items"]["$ref"].split('/')
-            object_ = check_collection(
-                class_location[2], global_, obj["schema"], path)
-            if object_["class_name"] == "":
-                # cannot parse because method not supported
-                return object_["class_name"]
-            get_class_details(
-                global_,
-                get_data_at_location(
-                    class_location,
-                    global_["doc"]),
-                get_class_name(class_location),
-                path=path)
-            return class_location[2]
-        except KeyError:
-            pass
+                pass
     # cannot parse because no external ref
+
+    print("Cannot parse path" + path + " because no ref to local class provided")
     return ""
 
 
@@ -309,24 +354,6 @@ def allow_parameter(parameter: Dict[str, Any])->bool:
     return True
 
 
-def type_ref_mapping(type: str)->str:
-    """
-    Returns semantic ref for OAS data types
-    :param type: data type
-    :return: ref
-    """
-    dataType_ref_map = dict()
-    # todo add support for byte , binary , password ,double data types
-    dataType_ref_map["integer"] = "https://schema.org/Integer"
-    dataType_ref_map["string"] = "https://schema.org/Text"
-    dataType_ref_map["long"] = "http://books.xmlschemata.org/relaxng/ch19-77199.html"
-    dataType_ref_map["float"] = "https://schema.org/Float"
-    dataType_ref_map["boolean"] = "https://schema.org/Boolean"
-    dataType_ref_map["dateTime"] = "https://schema.org/DateTime"
-    dataType_ref_map["date"] = "https://schema.org/Date"
-    return dataType_ref_map[type]
-
-
 def get_parameters(global_: Dict[str, Any],
                    path: str, method: str, class_name: str)->str:
     """
@@ -339,9 +366,11 @@ def get_parameters(global_: Dict[str, Any],
     """
     param = str
     for parameter in global_["doc"]["paths"][path][method]["parameters"]:
+        # will call schema_parse with class name and schema block after checking if type exists
+        # coz there are instances where no schema key is present
         if allow_parameter(parameter):
             try:
-                # check if class has been parsed
+                # check if class has been pared
                 if parameter["schema"]["$ref"].split(
                         '/')[2] in global_["class_names"]:
                     param = "vocab:" + \
@@ -358,26 +387,7 @@ def get_parameters(global_: Dict[str, Any],
                     param = "vocab:" + \
                             parameter["schema"]["$ref"].split('/')[2]
             except KeyError:
-                type = parameter["type"]
-                if type == "array":
-                    # TODO change this after we find a way to represent array
-                    # in parameter using semantics
-                    items = parameter["schema"]["items"]
-                    try:
-                        if items["$ref"].split(
-                                '/')[2] in global_["class_names"]:
-                            param = "vocab" + items["$ref"].split('/')[2]
-                        else:
-                            get_class_details(
-                                global_, get_data_at_location(
-                                    items["$ref"]), items["$ref"].split('/')[2], path=path)
-                            param = "vocab" + items["$ref"].split('/')[2]
-                    except KeyError:
-                        param = type_ref_mapping(items["type"])
-                elif type == "object":
-                    param = "string"
-                else:
-                    param = type_ref_mapping(type)
+                param = ""
 
     return param
 
@@ -391,42 +401,46 @@ def get_ops(global_: Dict[str, Any], path: str,
     :param method: method block
     :param class_name:class name
     """
-    op_method = method
-    op_expects = None
-    op_name = try_catch_replacement(
-        global_["doc"]["paths"][path][method],
-        "summary",
-        class_name)
-    op_status = list()
-    op_expects = get_parameters(global_, path, method, class_name)
-    try:
-        responses = global_["doc"]["paths"][path][method]["responses"]
-        op_returns = None
-        for response in responses:
-            if response != 'default':
-                op_status.append({"statusCode": int(
-                    response), "description": responses[response]["description"]})
-            try:
-                op_returns = "vocab:" + \
-                    responses[response]["schema"]["$ref"].split('/')[2]
-            except KeyError:
-                pass
-            if op_returns is None:
+    if method not in global_[class_name]["methods"]:
+        op_method = method
+
+        op_expects = None
+        op_name = try_catch_replacement(
+            global_["doc"]["paths"][path][method],
+            "summary",
+            class_name)
+        op_status = list()
+        op_expects = get_parameters(global_, path, method, class_name)
+        try:
+            responses = global_["doc"]["paths"][path][method]["responses"]
+            op_returns = None
+            for response in responses:
+                if response != 'default':
+                    op_status.append({"statusCode": int(
+                        response), "description": responses[response]["description"]})
                 try:
                     op_returns = "vocab:" + \
-                        responses[response]["schema"]["items"]["$ref"].split(
-                            '/')[2]
+                        responses[response]["schema"]["$ref"].split('/')[2]
                 except KeyError:
-                    op_returns = try_catch_replacement(
-                        responses[response]["schema"], "type", None)
-    except KeyError:
-        op_returns = None
-    if len(op_status) == 0:
-        op_status.append(
-            {"statusCode": 200, "description": "Successful Operation"})
-
-    global_[class_name]["op_definition"].append(HydraClassOp(
-        op_name, op_method.upper(), op_expects, op_returns, op_status))
+                    pass
+                if op_returns is None:
+                    try:
+                        op_returns = "vocab:" + \
+                            responses[response]["schema"]["items"]["$ref"].split(
+                                '/')[2]
+                    except KeyError:
+                        op_returns = try_catch_replacement(
+                            responses[response]["schema"], "type", None)
+        except KeyError:
+            op_returns = None
+        if len(op_status) == 0:
+            op_status.append(
+                {"statusCode": 200, "description": "Successful Operation"})
+        global_[class_name]["methods"].add(method)
+        global_[class_name]["op_definition"].append(HydraClassOp(
+            op_name, op_method.upper(), op_expects, op_returns, op_status))
+    else:
+        print("Method on path" + path + " already present !")
 
 
 def get_paths(global_: Dict[str, Any]) -> None:
@@ -461,8 +475,8 @@ def parse(doc: Dict[str, Any]) -> str:
     else:
         desc = "not defined"
         title = "not defined"
-    # todo throw error if desc or title dont exist
-
+        print("Desc and title not present hence exit")
+        sys.exit()
     baseURL = try_catch_replacement(doc, "host", "localhost")
     name = try_catch_replacement(doc, "basePath", "api")
     schemes = try_catch_replacement(doc, "schemes", "http")
@@ -473,7 +487,7 @@ def parse(doc: Dict[str, Any]) -> str:
             global_[name]["class_definition"].add_supported_prop(prop)
         for op in global_[name]["op_definition"]:
             global_[name]["class_definition"].add_supported_op(op)
-        if global_[name]["collection"] is True :
+        if global_[name]["collection"] is True:
             if global_[name]["class_definition"].endpoint is True:
                 global_[name]["class_definition"].endpoint = False
 
diff --git a/hydrus/samples/hydra_doc_sample.py b/hydrus/samples/hydra_doc_sample.py
index 69fc58c..95d4b09 100644
--- a/hydrus/samples/hydra_doc_sample.py
+++ b/hydrus/samples/hydra_doc_sample.py
@@ -52,28 +52,109 @@ doc = {
     "possibleStatus": [],
     "supportedClass": [
         {
-            "@id": "vocab:Pet",
+            "@id": "vocab:ApiResponse",
             "@type": "hydra:Class",
-            "description": "Pet",
+            "description": "ApiResponse",
             "supportedOperation": [
                 {
                     "@type": "http://schema.org/UpdateAction",
-                    "expects": "vocab:Pet",
+                    "expects": "",
                     "method": "POST",
                     "possibleStatus": [
                         {
-                            "description": "Invalid input",
-                            "statusCode": 405
+                            "description": "successful operation",
+                            "statusCode": 200
+                        }
+                    ],
+                    "returns": "vocab:ApiResponse",
+                    "title": "uploads an image"
+                }
+            ],
+            "supportedProperty": [
+                {
+                    "@type": "SupportedProperty",
+                    "property": "",
+                    "readonly": "true",
+                    "required": "false",
+                    "title": "code",
+                    "writeonly": "true"
+                },
+                {
+                    "@type": "SupportedProperty",
+                    "property": "",
+                    "readonly": "true",
+                    "required": "false",
+                    "title": "type",
+                    "writeonly": "true"
+                },
+                {
+                    "@type": "SupportedProperty",
+                    "property": "",
+                    "readonly": "true",
+                    "required": "false",
+                    "title": "message",
+                    "writeonly": "true"
+                }
+            ],
+            "title": "ApiResponse"
+        },
+        {
+            "@id": "vocab:User",
+            "@type": "hydra:Class",
+            "description": "User",
+            "supportedOperation": [
+                {
+                    "@type": "http://schema.org/UpdateAction",
+                    "expects": "vocab:User",
+                    "method": "POST",
+                    "possibleStatus": [
+                        {
+                            "description": "Successful Operation",
+                            "statusCode": 200
                         }
                     ],
                     "returns": "null",
-                    "title": "Add a new pet to the store"
+                    "title": "Create user"
+                },
+                {
+                    "@type": "http://schema.org/FindAction",
+                    "expects": "",
+                    "method": "GET",
+                    "possibleStatus": [
+                        {
+                            "description": "successful operation",
+                            "statusCode": 200
+                        },
+                        {
+                            "description": "Invalid username supplied",
+                            "statusCode": 400
+                        },
+                        {
+                            "description": "User not found",
+                            "statusCode": 404
+                        }
+                    ],
+                    "returns": "vocab:User",
+                    "title": "Get user by user name"
+                },
+                {
+                    "@type": "http://schema.org/AddAction",
+                    "expects": "vocab:User",
+                    "method": "PUT",
+                    "possibleStatus": [
+                        {
+                            "description": "Invalid user supplied",
+                            "statusCode": 400
+                        }
+                    ],
+                    "returns": "null",
+                    "title": "Updated user"
                 }
             ],
             "supportedProperty": [
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:id",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "id",
@@ -81,46 +162,62 @@ doc = {
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:category",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
-                    "title": "category",
+                    "title": "username",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:name",
+                    "property": "",
                     "readonly": "true",
-                    "required": "true",
-                    "title": "name",
+                    "required": "false",
+                    "title": "firstName",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:photoUrls",
+                    "property": "",
                     "readonly": "true",
-                    "required": "true",
-                    "title": "photoUrls",
+                    "required": "false",
+                    "title": "lastName",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:tags",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
-                    "title": "tags",
+                    "title": "email",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:status",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
-                    "title": "status",
+                    "title": "password",
+                    "writeonly": "true"
+                },
+                {
+                    "@type": "SupportedProperty",
+                    "property": "",
+                    "readonly": "true",
+                    "required": "false",
+                    "title": "phone",
+                    "writeonly": "true"
+                },
+                {
+                    "@type": "SupportedProperty",
+                    "property": "",
+                    "readonly": "true",
+                    "required": "false",
+                    "title": "userStatus",
                     "writeonly": "true"
                 }
             ],
-            "title": "Pet"
+            "title": "User"
         },
         {
             "@id": "vocab:Order",
@@ -143,12 +240,33 @@ doc = {
                     ],
                     "returns": "vocab:Order",
                     "title": "Place an order for a pet"
+                },
+                {
+                    "@type": "http://schema.org/FindAction",
+                    "expects": "",
+                    "method": "GET",
+                    "possibleStatus": [
+                        {
+                            "description": "successful operation",
+                            "statusCode": 200
+                        },
+                        {
+                            "description": "Invalid ID supplied",
+                            "statusCode": 400
+                        },
+                        {
+                            "description": "Order not found",
+                            "statusCode": 404
+                        }
+                    ],
+                    "returns": "vocab:Order",
+                    "title": "Find purchase order by ID"
                 }
             ],
             "supportedProperty": [
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:id",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "id",
@@ -156,7 +274,7 @@ doc = {
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:petId",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "petId",
@@ -164,7 +282,7 @@ doc = {
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:quantity",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "quantity",
@@ -172,7 +290,7 @@ doc = {
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:shipDate",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "shipDate",
@@ -180,7 +298,7 @@ doc = {
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:status",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "status",
@@ -188,7 +306,7 @@ doc = {
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:complete",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "complete",
@@ -198,28 +316,54 @@ doc = {
             "title": "Order"
         },
         {
-            "@id": "vocab:User",
+            "@id": "vocab:Pet",
             "@type": "hydra:Class",
-            "description": "User",
+            "description": "Pet",
             "supportedOperation": [
                 {
                     "@type": "http://schema.org/UpdateAction",
-                    "expects": "vocab:User",
+                    "expects": "vocab:Pet",
                     "method": "POST",
                     "possibleStatus": [
                         {
-                            "description": "Successful Operation",
-                            "statusCode": 200
+                            "description": "Invalid input",
+                            "statusCode": 405
                         }
                     ],
                     "returns": "null",
-                    "title": "Create user"
+                    "title": "Add a new pet to the store"
+                },
+                {
+                    "@type": "http://schema.org/AddAction",
+                    "expects": "vocab:Pet",
+                    "method": "PUT",
+                    "possibleStatus": [
+                        {
+                            "description": "Invalid ID supplied",
+                            "statusCode": 400
+                        }
+                    ],
+                    "returns": "null",
+                    "title": "Update an existing pet"
+                },
+                {
+                    "@type": "http://schema.org/FindAction",
+                    "expects": "",
+                    "method": "GET",
+                    "possibleStatus": [
+                        {
+                            "description": "successful operation",
+                            "statusCode": 200
+                        }
+                    ],
+                    "returns": "vocab:Pet",
+                    "title": "get all pets"
                 }
             ],
             "supportedProperty": [
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:id",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
                     "title": "id",
@@ -227,62 +371,46 @@ doc = {
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:username",
-                    "readonly": "true",
-                    "required": "false",
-                    "title": "username",
-                    "writeonly": "true"
-                },
-                {
-                    "@type": "SupportedProperty",
-                    "property": "vocab:firstName",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
-                    "title": "firstName",
-                    "writeonly": "true"
-                },
-                {
-                    "@type": "SupportedProperty",
-                    "property": "vocab:lastName",
-                    "readonly": "true",
-                    "required": "false",
-                    "title": "lastName",
+                    "title": "category",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:email",
+                    "property": "",
                     "readonly": "true",
-                    "required": "false",
-                    "title": "email",
+                    "required": "true",
+                    "title": "name",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:password",
+                    "property": "",
                     "readonly": "true",
-                    "required": "false",
-                    "title": "password",
+                    "required": "true",
+                    "title": "photoUrls",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:phone",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
-                    "title": "phone",
+                    "title": "tags",
                     "writeonly": "true"
                 },
                 {
                     "@type": "SupportedProperty",
-                    "property": "vocab:userStatus",
+                    "property": "",
                     "readonly": "true",
                     "required": "false",
-                    "title": "userStatus",
+                    "title": "status",
                     "writeonly": "true"
                 }
             ],
-            "title": "User"
+            "title": "Pet"
         },
         {
             "@id": "http://www.w3.org/ns/hydra/core#Collection",
@@ -310,73 +438,30 @@ doc = {
             "title": "Resource"
         },
         {
-            "@id": "vocab:PetCollection",
-            "@type": "hydra:Class",
-            "description": "A collection of pet",
-            "subClassOf": "http://www.w3.org/ns/hydra/core#Collection",
-            "supportedOperation": [
-                {
-                    "@id": "_:pet_collection_retrieve",
-                    "@type": "http://schema.org/FindAction",
-                    "description": "Retrieves all Pet entities",
-                    "expects": "null",
-                    "method": "GET",
-                    "returns": "vocab:PetCollection",
-                    "statusCodes": []
-                },
-                {
-                    "@id": "_:pet_create",
-                    "@type": "http://schema.org/AddAction",
-                    "description": "Create new Pet entitity",
-                    "expects": "vocab:Pet",
-                    "method": "PUT",
-                    "returns": "vocab:Pet",
-                    "statusCodes": [
-                        {
-                            "description": "If the Pet entity was created successfully.",
-                            "statusCode": 201
-                        }
-                    ]
-                }
-            ],
-            "supportedProperty": [
-                {
-                    "@type": "SupportedProperty",
-                    "description": "The pet",
-                    "property": "http://www.w3.org/ns/hydra/core#member",
-                    "readonly": "false",
-                    "required": "false",
-                    "title": "members",
-                    "writeonly": "false"
-                }
-            ],
-            "title": "PetCollection"
-        },
-        {
-            "@id": "vocab:OrderCollection",
+            "@id": "vocab:UserCollection",
             "@type": "hydra:Class",
-            "description": "A collection of order",
+            "description": "A collection of user",
             "subClassOf": "http://www.w3.org/ns/hydra/core#Collection",
             "supportedOperation": [
                 {
-                    "@id": "_:order_collection_retrieve",
+                    "@id": "_:user_collection_retrieve",
                     "@type": "http://schema.org/FindAction",
-                    "description": "Retrieves all Order entities",
+                    "description": "Retrieves all User entities",
                     "expects": "null",
                     "method": "GET",
-                    "returns": "vocab:OrderCollection",
+                    "returns": "vocab:UserCollection",
                     "statusCodes": []
                 },
                 {
-                    "@id": "_:order_create",
+                    "@id": "_:user_create",
                     "@type": "http://schema.org/AddAction",
-                    "description": "Create new Order entitity",
-                    "expects": "vocab:Order",
+                    "description": "Create new User entitity",
+                    "expects": "vocab:User",
                     "method": "PUT",
-                    "returns": "vocab:Order",
+                    "returns": "vocab:User",
                     "statusCodes": [
                         {
-                            "description": "If the Order entity was created successfully.",
+                            "description": "If the User entity was created successfully.",
                             "statusCode": 201
                         }
                     ]
@@ -385,7 +470,7 @@ doc = {
             "supportedProperty": [
                 {
                     "@type": "SupportedProperty",
-                    "description": "The order",
+                    "description": "The user",
                     "property": "http://www.w3.org/ns/hydra/core#member",
                     "readonly": "false",
                     "required": "false",
@@ -393,33 +478,33 @@ doc = {
                     "writeonly": "false"
                 }
             ],
-            "title": "OrderCollection"
+            "title": "UserCollection"
         },
         {
-            "@id": "vocab:UserCollection",
+            "@id": "vocab:PetCollection",
             "@type": "hydra:Class",
-            "description": "A collection of user",
+            "description": "A collection of pet",
             "subClassOf": "http://www.w3.org/ns/hydra/core#Collection",
             "supportedOperation": [
                 {
-                    "@id": "_:user_collection_retrieve",
+                    "@id": "_:pet_collection_retrieve",
                     "@type": "http://schema.org/FindAction",
-                    "description": "Retrieves all User entities",
+                    "description": "Retrieves all Pet entities",
                     "expects": "null",
                     "method": "GET",
-                    "returns": "vocab:UserCollection",
+                    "returns": "vocab:PetCollection",
                     "statusCodes": []
                 },
                 {
-                    "@id": "_:user_create",
+                    "@id": "_:pet_create",
                     "@type": "http://schema.org/AddAction",
-                    "description": "Create new User entitity",
-                    "expects": "vocab:User",
+                    "description": "Create new Pet entitity",
+                    "expects": "vocab:Pet",
                     "method": "PUT",
-                    "returns": "vocab:User",
+                    "returns": "vocab:Pet",
                     "statusCodes": [
                         {
-                            "description": "If the User entity was created successfully.",
+                            "description": "If the Pet entity was created successfully.",
                             "statusCode": 201
                         }
                     ]
@@ -428,7 +513,7 @@ doc = {
             "supportedProperty": [
                 {
                     "@type": "SupportedProperty",
-                    "description": "The user",
+                    "description": "The pet",
                     "property": "http://www.w3.org/ns/hydra/core#member",
                     "readonly": "false",
                     "required": "false",
@@ -436,7 +521,7 @@ doc = {
                     "writeonly": "false"
                 }
             ],
-            "title": "UserCollection"
+            "title": "PetCollection"
         },
         {
             "@id": "vocab:EntryPoint",
@@ -455,36 +540,28 @@ doc = {
             ],
             "supportedProperty": [
                 {
-                    "hydra:description": "The PetCollection collection",
-                    "hydra:title": "petcollection",
+                    "hydra:description": "The ApiResponse Class",
+                    "hydra:title": "apiresponse",
                     "property": {
-                        "@id": "vocab:EntryPoint/pet",
+                        "@id": "vocab:EntryPoint//pet/uploadImage",
                         "@type": "hydra:Link",
-                        "description": "The PetCollection collection",
+                        "description": "ApiResponse",
                         "domain": "vocab:EntryPoint",
-                        "label": "PetCollection",
-                        "range": "vocab:PetCollection",
+                        "label": "ApiResponse",
+                        "range": "vocab:ApiResponse",
                         "supportedOperation": [
                             {
-                                "@id": "_:_:pet_collection_retrieve",
-                                "@type": "http://schema.org/FindAction",
-                                "description": "Retrieves all Pet entities",
-                                "expects": "null",
-                                "method": "GET",
-                                "returns": "vocab:PetCollection",
-                                "statusCodes": []
-                            },
-                            {
-                                "@id": "_:_:pet_create",
-                                "@type": "http://schema.org/AddAction",
-                                "description": "Create new Pet entitity",
-                                "expects": "vocab:Pet",
-                                "method": "PUT",
-                                "returns": "vocab:Pet",
+                                "@id": "uploads an image",
+                                "@type": "http://schema.org/UpdateAction",
+                                "description": "null",
+                                "expects": "",
+                                "label": "uploads an image",
+                                "method": "POST",
+                                "returns": "vocab:ApiResponse",
                                 "statusCodes": [
                                     {
-                                        "description": "If the Pet entity was created successfully.",
-                                        "statusCode": 201
+                                        "description": "successful operation",
+                                        "statusCode": 200
                                     }
                                 ]
                             }
@@ -495,36 +572,55 @@ doc = {
                     "writeonly": "false"
                 },
                 {
-                    "hydra:description": "The OrderCollection collection",
-                    "hydra:title": "ordercollection",
+                    "hydra:description": "The Order Class",
+                    "hydra:title": "order",
                     "property": {
-                        "@id": "vocab:EntryPoint/store/order",
+                        "@id": "vocab:EntryPoint//store/order",
                         "@type": "hydra:Link",
-                        "description": "The OrderCollection collection",
+                        "description": "this is def",
                         "domain": "vocab:EntryPoint",
-                        "label": "OrderCollection",
-                        "range": "vocab:OrderCollection",
+                        "label": "Order",
+                        "range": "vocab:Order",
                         "supportedOperation": [
                             {
-                                "@id": "_:_:order_collection_retrieve",
-                                "@type": "http://schema.org/FindAction",
-                                "description": "Retrieves all Order entities",
-                                "expects": "null",
-                                "method": "GET",
-                                "returns": "vocab:OrderCollection",
-                                "statusCodes": []
+                                "@id": "place an order for a pet",
+                                "@type": "http://schema.org/UpdateAction",
+                                "description": "null",
+                                "expects": "vocab:Order",
+                                "label": "Place an order for a pet",
+                                "method": "POST",
+                                "returns": "vocab:Order",
+                                "statusCodes": [
+                                    {
+                                        "description": "successful operation",
+                                        "statusCode": 200
+                                    },
+                                    {
+                                        "description": "Invalid Order",
+                                        "statusCode": 400
+                                    }
+                                ]
                             },
                             {
-                                "@id": "_:_:order_create",
-                                "@type": "http://schema.org/AddAction",
-                                "description": "Create new Order entitity",
-                                "expects": "vocab:Order",
-                                "method": "PUT",
+                                "@id": "find purchase order by id",
+                                "@type": "http://schema.org/FindAction",
+                                "description": "null",
+                                "expects": "",
+                                "label": "Find purchase order by ID",
+                                "method": "GET",
                                 "returns": "vocab:Order",
                                 "statusCodes": [
                                     {
-                                        "description": "If the Order entity was created successfully.",
-                                        "statusCode": 201
+                                        "description": "successful operation",
+                                        "statusCode": 200
+                                    },
+                                    {
+                                        "description": "Invalid ID supplied",
+                                        "statusCode": 400
+                                    },
+                                    {
+                                        "description": "Order not found",
+                                        "statusCode": 404
                                     }
                                 ]
                             }
@@ -538,7 +634,7 @@ doc = {
                     "hydra:description": "The UserCollection collection",
                     "hydra:title": "usercollection",
                     "property": {
-                        "@id": "vocab:EntryPoint/user",
+                        "@id": "vocab:EntryPoint//user",
                         "@type": "hydra:Link",
                         "description": "The UserCollection collection",
                         "domain": "vocab:EntryPoint",
@@ -546,7 +642,7 @@ doc = {
                         "range": "vocab:UserCollection",
                         "supportedOperation": [
                             {
-                                "@id": "_:_:user_collection_retrieve",
+                                "@id": "_:user_collection_retrieve",
                                 "@type": "http://schema.org/FindAction",
                                 "description": "Retrieves all User entities",
                                 "expects": "null",
@@ -555,7 +651,7 @@ doc = {
                                 "statusCodes": []
                             },
                             {
-                                "@id": "_:_:user_create",
+                                "@id": "_:user_create",
                                 "@type": "http://schema.org/AddAction",
                                 "description": "Create new User entitity",
                                 "expects": "vocab:User",
@@ -573,6 +669,46 @@ doc = {
                     "readonly": "true",
                     "required": "null",
                     "writeonly": "false"
+                },
+                {
+                    "hydra:description": "The PetCollection collection",
+                    "hydra:title": "petcollection",
+                    "property": {
+                        "@id": "vocab:EntryPoint//pet",
+                        "@type": "hydra:Link",
+                        "description": "The PetCollection collection",
+                        "domain": "vocab:EntryPoint",
+                        "label": "PetCollection",
+                        "range": "vocab:PetCollection",
+                        "supportedOperation": [
+                            {
+                                "@id": "_:pet_collection_retrieve",
+                                "@type": "http://schema.org/FindAction",
+                                "description": "Retrieves all Pet entities",
+                                "expects": "null",
+                                "method": "GET",
+                                "returns": "vocab:PetCollection",
+                                "statusCodes": []
+                            },
+                            {
+                                "@id": "_:pet_create",
+                                "@type": "http://schema.org/AddAction",
+                                "description": "Create new Pet entitity",
+                                "expects": "vocab:Pet",
+                                "method": "PUT",
+                                "returns": "vocab:Pet",
+                                "statusCodes": [
+                                    {
+                                        "description": "If the Pet entity was created successfully.",
+                                        "statusCode": 201
+                                    }
+                                ]
+                            }
+                        ]
+                    },
+                    "readonly": "true",
+                    "required": "null",
+                    "writeonly": "false"
                 }
             ],
             "title": "EntryPoint"
diff --git a/petstore_openapi.yaml b/petstore_openapi.yaml
new file mode 100644
index 0000000..7748094
--- /dev/null
+++ b/petstore_openapi.yaml
@@ -0,0 +1,724 @@
+swagger:                          '2.0'
+info:
+  description:                    'This is a sample server Petstore server.  You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).  For this sample, you can use the api key `special-key` to test the authorization filters.'
+  version:                        1.0.0
+  title:                          Swagger Petstore
+  termsOfService:                 'http://swagger.io/terms/'
+  contact:
+    email:                        apiteam@swagger.io
+  license:
+    name:                         Apache 2.0
+    url:                          'http://www.apache.org/licenses/LICENSE-2.0.html'
+host:                             petstore.swagger.io
+basePath:                         /v2
+tags:
+  - name:                         pet
+    description:                  Everything about your Pets
+    externalDocs:
+      description:                Find out more
+      url:                        'http://swagger.io'
+  - name:                         store
+    description:                  Access to Petstore orders
+  - name:                         user
+    description:                  Operations about user
+    externalDocs:
+      description:                Find out more about our store
+      url:                        'http://swagger.io'
+schemes:
+  - http
+paths:
+  /pet:
+    post:
+      tags:
+        - pet
+      summary:                    Add a new pet to the store
+      description:                ''
+      operationId:                addPet
+      consumes:
+        - application/json
+        - application/xml
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - in:                     body
+          name:                   body
+          description:            Pet object that needs to be added to the store
+          required:               true
+          schema:
+            $ref:                 '#/definitions/Pet'
+      responses:
+        '405':
+          description:            Invalid input
+      security:
+        - petstore_auth:
+            - 'write:pets'
+            - 'read:pets'
+    put:
+      tags:
+        - pet
+      summary:                    Update an existing pet
+      description:                ''
+      operationId:                updatePet
+      consumes:
+        - application/json
+        - application/xml
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - in:                     body
+          name:                   body
+          description:            Pet object that needs to be added to the store
+          required:               true
+          schema:
+            $ref:                 '#/definitions/Pet'
+      responses:
+        '400':
+          description:            Invalid ID supplied
+        '404':
+          description:            Pet not found
+        '405':
+          description:            Validation exception
+      security:
+        - petstore_auth:
+            - 'write:pets'
+            - 'read:pets'
+    get:
+      summary:                    get all pets
+      description:                get all pets
+      parameters:
+        - name:                   status
+          in:                     query
+          description:            Status values that need to be considered for filter
+          required:               true
+          type:                   array
+          items:
+            type:                 string
+            enum:
+              - available
+              - pending
+              - sold
+            default:              available
+          collectionFormat:       multi
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            type:                 array
+            items:
+              $ref:               '#/definitions/Pet'
+  /pet/findByStatus:
+    get:
+      tags:
+        - pet
+      summary:                    Finds Pets by status
+      description:                Multiple status values can be provided with comma separated strings
+      operationId:                findPetsByStatus
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   status
+          in:                     query
+          description:            Status values that need to be considered for filter
+          required:               true
+          type:                   array
+          items:
+            type:                 string
+            enum:
+              - available
+              - pending
+              - sold
+            default:              available
+          collectionFormat:       multi
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            type:                 array
+            items:
+              $ref:               '#/definitions/Pet'
+        '400':
+          description:            Invalid status value
+      security:
+        - petstore_auth:
+            - 'write:pets'
+            - 'read:pets'
+  /pet/findByTags:
+    get:
+      tags:
+        - pet
+      summary:                    Finds Pets by tags
+      description:                'Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.'
+      operationId:                findPetsByTags
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   tags
+          in:                     query
+          description:            Tags to filter by
+          required:               true
+          type:                   array
+          items:
+            type:                 string
+          collectionFormat:       multi
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            type:                 array
+            items:
+              $ref:               '#/definitions/Pet'
+        '400':
+          description:            Invalid tag value
+      security:
+        - petstore_auth:
+            - 'write:pets'
+            - 'read:pets'
+      deprecated:                 true
+  '/pet/{petId}':
+    get:
+      tags:
+        - pet
+      summary:                    Find pet by ID
+      description:                Returns a single pet
+      operationId:                getPetById
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   petId
+          in:                     path
+          description:            ID of pet to return
+          required:               true
+          type:                   integer
+          format:                 int64
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            $ref:                 '#/definitions/Pet'
+        '400':
+          description:            Invalid ID supplied
+        '404':
+          description:            Pet not found
+      security:
+        - api_key:                []
+    post:
+      tags:
+        - pet
+      summary:                    Updates a pet in the store with form data
+      description:                ''
+      operationId:                updatePetWithForm
+      consumes:
+        - application/x-www-form-urlencoded
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   petId
+          in:                     path
+          description:            ID of pet that needs to be updated
+          required:               true
+          type:                   integer
+          format:                 int64
+        - name:                   name
+          in:                     formData
+          description:            Updated name of the pet
+          required:               false
+          type:                   string
+        - name:                   status
+          in:                     formData
+          description:            Updated status of the pet
+          required:               false
+          type:                   string
+      responses:
+        '405':
+          description:            Invalid input
+      security:
+        - petstore_auth:
+            - 'write:pets'
+            - 'read:pets'
+    delete:
+      tags:
+        - pet
+      summary:                    Deletes a pet
+      description:                ''
+      operationId:                deletePet
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   api_key
+          in:                     header
+          required:               false
+          type:                   string
+        - name:                   petId
+          in:                     path
+          description:            Pet id to delete
+          required:               true
+          type:                   integer
+          format:                 int64
+      responses:
+        '400':
+          description:            Invalid ID supplied
+        '404':
+          description:            Pet not found
+      security:
+        - petstore_auth:
+            - 'write:pets'
+            - 'read:pets'
+  '/pet/{petId}/uploadImage':
+    post:
+      tags:
+        - pet
+      summary:                    uploads an image
+      description:                ''
+      operationId:                uploadFile
+      consumes:
+        - multipart/form-data
+      produces:
+        - application/json
+      parameters:
+        - name:                   petId
+          in:                     path
+          description:            ID of pet to update
+          required:               true
+          type:                   integer
+          format:                 int64
+        - name:                   additionalMetadata
+          in:                     formData
+          description:            Additional data to pass to server
+          required:               false
+          type:                   string
+        - name:                   file
+          in:                     formData
+          description:            file to upload
+          required:               false
+          type:                   file
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            $ref:                 '#/definitions/ApiResponse'
+      security:
+        - petstore_auth:
+            - 'write:pets'
+            - 'read:pets'
+  /store/inventory:
+    get:
+      tags:
+        - store
+      summary:                    Returns pet inventories by status
+      description:                Returns a map of status codes to quantities
+      operationId:                getInventory
+      produces:
+        - application/json
+      parameters:                 []
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            type:                 object
+            additionalProperties:
+              type:               integer
+              format:             int32
+      security:
+        - api_key:                []
+  /store/order:
+    post:
+      tags:
+        - store
+      summary:                    Place an order for a pet
+      description:                ''
+      operationId:                placeOrder
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - in:                     body
+          name:                   body
+          description:            order placed for purchasing the pet
+          required:               true
+          schema:
+            $ref:                 '#/definitions/Order'
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            $ref:                 '#/definitions/Order'
+        '400':
+          description:            Invalid Order
+  '/store/order/{orderId}':
+    get:
+      tags:
+        - store
+      summary:                    Find purchase order by ID
+      description:                For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions
+      operationId:                getOrderById
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   orderId
+          in:                     path
+          description:            ID of pet that needs to be fetched
+          required:               true
+          type:                   integer
+          maximum:                10
+          minimum:                1
+          format:                 int64
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            $ref:                 '#/definitions/Order'
+        '400':
+          description:            Invalid ID supplied
+        '404':
+          description:            Order not found
+    delete:
+      tags:
+        - store
+      summary:                    Delete purchase order by ID
+      description:                For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors
+      operationId:                deleteOrder
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   orderId
+          in:                     path
+          description:            ID of the order that needs to be deleted
+          required:               true
+          type:                   integer
+          minimum:                1
+          format:                 int64
+      responses:
+        '400':
+          description:            Invalid ID supplied
+        '404':
+          description:            Order not found
+  /user:
+    post:
+      tags:
+        - user
+      summary:                    Create user
+      description:                This can only be done by the logged in user.
+      operationId:                createUser
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - in:                     body
+          name:                   body
+          description:            Created user object
+          required:               true
+          schema:
+            $ref:                 '#/definitions/User'
+      responses:
+        default:
+          description:            successful operation
+  /user/createWithArray:
+    post:
+      tags:
+        - user
+      summary:                    Creates list of users with given input array
+      description:                ''
+      operationId:                createUsersWithArrayInput
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - in:                     body
+          name:                   body
+          description:            List of user object
+          required:               true
+          schema:
+            type:                 array
+            items:
+              $ref:               '#/definitions/User'
+      responses:
+        default:
+          description:            successful operation
+  /user/createWithList:
+    post:
+      tags:
+        - user
+      summary:                    Creates list of users with given input array
+      description:                ''
+      operationId:                createUsersWithListInput
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - in:                     body
+          name:                   body
+          description:            List of user object
+          required:               true
+          schema:
+            type:                 array
+            items:
+              $ref:               '#/definitions/User'
+      responses:
+        default:
+          description:            successful operation
+  /user/login:
+    get:
+      tags:
+        - user
+      summary:                    Logs user into the system
+      description:                ''
+      operationId:                loginUser
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   username
+          in:                     query
+          description:            The user name for login
+          required:               true
+          type:                   string
+        - name:                   password
+          in:                     query
+          description:            The password for login in clear text
+          required:               true
+          type:                   string
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            type:                 string
+          headers:
+            X-Rate-Limit:
+              type:               integer
+              format:             int32
+              description:        calls per hour allowed by the user
+            X-Expires-After:
+              type:               string
+              format:             date-time
+              description:        date in UTC when token expires
+        '400':
+          description:            Invalid username/password supplied
+  /user/logout:
+    get:
+      tags:
+        - user
+      summary:                    Logs out current logged in user session
+      description:                ''
+      operationId:                logoutUser
+      produces:
+        - application/xml
+        - application/json
+      parameters:                 []
+      responses:
+        default:
+          description:            successful operation
+  '/user/{username}':
+    get:
+      tags:
+        - user
+      summary:                    Get user by user name
+      description:                ''
+      operationId:                getUserByName
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   username
+          in:                     path
+          description:            'The name that needs to be fetched. Use user1 for testing. '
+          required:               true
+          type:                   string
+      responses:
+        '200':
+          description:            successful operation
+          schema:
+            $ref:                 '#/definitions/User'
+        '400':
+          description:            Invalid username supplied
+        '404':
+          description:            User not found
+    put:
+      tags:
+        - user
+      summary:                    Updated user
+      description:                This can only be done by the logged in user.
+      operationId:                updateUser
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   username
+          in:                     path
+          description:            name that need to be updated
+          required:               true
+          type:                   string
+        - in:                     body
+          name:                   body
+          description:            Updated user object
+          required:               true
+          schema:
+            $ref:                 '#/definitions/User'
+      responses:
+        '400':
+          description:            Invalid user supplied
+        '404':
+          description:            User not found
+    delete:
+      tags:
+        - user
+      summary:                    Delete user
+      description:                This can only be done by the logged in user.
+      operationId:                deleteUser
+      produces:
+        - application/xml
+        - application/json
+      parameters:
+        - name:                   username
+          in:                     path
+          description:            The name that needs to be deleted
+          required:               true
+          type:                   string
+      responses:
+        '400':
+          description:            Invalid username supplied
+        '404':
+          description:            User not found
+securityDefinitions:
+  petstore_auth:
+    type:                         oauth2
+    authorizationUrl:             'http://petstore.swagger.io/oauth/dialog'
+    flow:                         implicit
+    scopes:
+      'write:pets':               modify pets in your account
+      'read:pets':                read your pets
+  api_key:
+    type:                         apiKey
+    name:                         api_key
+    in:                           header
+definitions:
+  Order:
+    type:                         object
+    description:                  "this is def"
+    properties:
+      id:
+        type:                     integer
+        format:                   int64
+      petId:
+        type:                     integer
+        format:                   int64
+      quantity:
+        type:                     integer
+        format:                   int32
+      shipDate:
+        type:                     string
+        format:                   date-time
+      status:
+        type:                     string
+        description:              Order Status
+        enum:
+          - placed
+          - approved
+          - delivered
+      complete:
+        type:                     boolean
+        default:                  false
+    xml:
+      name:                       Order
+  User:
+    type:                         object
+    properties:
+      id:
+        type:                     integer
+        format:                   int64
+      username:
+        type:                     string
+      firstName:
+        type:                     string
+      lastName:
+        type:                     string
+      email:
+        type:                     string
+      password:
+        type:                     string
+      phone:
+        type:                     string
+      userStatus:
+        type:                     integer
+        format:                   int32
+        description:              User Status
+    xml:
+      name:                       User
+  Category:
+    type:                         object
+    properties:
+      id:
+        type:                     integer
+        format:                   int64
+      name:
+        type:                     string
+    xml:
+      name:                       Category
+  Tag:
+    type:                         object
+    properties:
+      id:
+        type:                     integer
+        format:                   int64
+      name:
+        type:                     string
+    xml:
+      name:                       Tag
+  Pet:
+    type:                         object
+    required:
+      - name
+      - photoUrls
+    properties:
+      id:
+        type:                     integer
+        format:                   int64
+      category:
+        $ref:                     '#/definitions/Category'
+      name:
+        type:                     string
+        example:                  doggie
+      photoUrls:
+        type:                     array
+        xml:
+          name:                   photoUrl
+          wrapped:                true
+        items:
+          type:                   string
+      tags:
+        type:                     array
+        xml:
+          name:                   tag
+          wrapped:                true
+        items:
+          $ref:                   '#/definitions/Tag'
+      status:
+        type:                     string
+        description:              pet status in the store
+        enum:
+          - available
+          - pending
+          - sold
+    xml:
+      name:                       Pet
+  ApiResponse:
+    type:                         object
+    properties:
+      code:
+        type:                     integer
+        format:                   int32
+      type:
+        type:                     string
+      message:
+        type:                     string
+externalDocs:
+  description:                    Find out more about Swagger
+  url:                            'http://swagger.io'


Test patch:
diff --git a/hydrus/tests/test_crud.py b/hydrus/tests/test_crud.py
index ef61624..a8d4dfb 100644
--- a/hydrus/tests/test_crud.py
+++ b/hydrus/tests/test_crud.py
@@ -8,7 +8,7 @@ import hydrus.data.crud as crud
 from hydrus.data.db_models import Base
 from hydrus.data import doc_parse
 from hydrus.hydraspec import doc_maker
-from hydrus.samples import doc_writer_sample
+from hydrus.samples.hydra_doc_sample import doc
 
 import random
 from typing import List
@@ -44,10 +44,17 @@ class TestCRUD(unittest.TestCase):
         self.API_NAME = "demoapi"
         self.HYDRUS_SERVER_URL = "http://hydrus.com/"
         self.session = session
+
         self.doc = doc_maker.create_doc(
-            doc_writer_sample.api_doc.generate(), self.HYDRUS_SERVER_URL, self.API_NAME)
+            doc, self.HYDRUS_SERVER_URL, self.API_NAME)
 
         test_classes = doc_parse.get_classes(self.doc.generate())
+
+        # Getting list of classes from APIDoc
+        self.doc_collection_classes = [self.doc.collections[i]["collection"].class_.title \
+            for i in self.doc.collections]
+        print(self.doc_collection_classes)
+        print(random.choice(self.doc_collection_classes))
         test_properties = doc_parse.get_all_properties(test_classes)
         doc_parse.insert_classes(test_classes, self.session)
         doc_parse.insert_properties(test_properties, self.session)
@@ -56,25 +63,25 @@ class TestCRUD(unittest.TestCase):
 
     def test_insert(self):
         """Test CRUD insert."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        response = crud.insert(object_=object_, id_=1, session=self.session)
-        assert isinstance(response, int)
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        response = crud.insert(object_=object_, id_="1", session=self.session)
+        assert isinstance(response, str)
 
     def test_get(self):
         """Test CRUD get."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        id_ = 2
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        id_ = "2"
         response = crud.insert(object_=object_, id_=id_, session=self.session)
         object_ = crud.get(id_=id_, type_=object_[
                            "@type"], session=self.session, api_name="api")
-        assert isinstance(response, int)
-        assert int(object_["@id"].split("/")[-1]) == id_
+        assert isinstance(response, str)
+        assert object_["@id"].split("/")[-1] == id_
 
     def test_update(self):
         """Test CRUD update."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        new_object = gen_dummy_object("dummyClass", self.doc)
-        id_ = 30
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        new_object = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        id_ = "30"
         insert_response = crud.insert(
             object_=object_, id_=id_, session=self.session)
         update_response = crud.update(
@@ -85,20 +92,20 @@ class TestCRUD(unittest.TestCase):
             api_name="api")
         test_object = crud.get(id_=id_, type_=object_[
                                "@type"], session=self.session, api_name="api")
-        assert isinstance(insert_response, int)
-        assert isinstance(update_response, int)
+        assert isinstance(insert_response, str)
+        assert isinstance(update_response, str)
         assert insert_response == update_response
-        assert int(test_object["@id"].split("/")[-1]) == id_
+        assert test_object["@id"].split("/")[-1] == id_
 
     def test_delete(self):
         """Test CRUD delete."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        id_ = 4
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        id_ = "4"
         insert_response = crud.insert(
             object_=object_, id_=id_, session=self.session)
         delete_response = crud.delete(
             id_=id_, type_=object_["@type"], session=self.session)
-        assert isinstance(insert_response, int)
+        assert isinstance(insert_response, str)
         response_code = None
         try:
             get_response = crud.get(
@@ -112,8 +119,8 @@ class TestCRUD(unittest.TestCase):
 
     def test_get_id(self):
         """Test CRUD get when wrong/undefined ID is given."""
-        id_ = 999
-        type_ = "dummyClass"
+        id_ = "999"
+        type_ = random.choice(self.doc_collection_classes)
         response_code = None
         try:
             get_response = crud.get(
@@ -124,7 +131,7 @@ class TestCRUD(unittest.TestCase):
 
     def test_get_type(self):
         """Test CRUD get when wrong/undefined class is given."""
-        id_ = 1
+        id_ = "1"
         type_ = "otherClass"
         response_code = None
         try:
@@ -136,11 +143,11 @@ class TestCRUD(unittest.TestCase):
 
     def test_delete_type(self):
         """Test CRUD delete when wrong/undefined class is given."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        id_ = 50
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        id_ = "50"
         insert_response = crud.insert(
             object_=object_, id_=id_, session=self.session)
-        assert isinstance(insert_response, int)
+        assert isinstance(insert_response, str)
         assert insert_response == id_
         response_code = None
         try:
@@ -152,8 +159,8 @@ class TestCRUD(unittest.TestCase):
 
     def test_delete_id(self):
         """Test CRUD delete when wrong/undefined ID is given."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        id_ = 6
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        id_ = "6"
         insert_response = crud.insert(
             object_=object_, id_=id_, session=self.session)
         response_code = None
@@ -163,13 +170,13 @@ class TestCRUD(unittest.TestCase):
         except Exception as e:
             response_code, message = e.get_HTTP()
         assert 404 == response_code
-        assert isinstance(insert_response, int)
+        assert isinstance(insert_response, str)
         assert insert_response == id_
 
     def test_insert_type(self):
         """Test CRUD insert when wrong/undefined class is given."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        id_ = 7
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        id_ = "7"
         object_["@type"] = "otherClass"
         response_code = None
         try:
@@ -181,8 +188,8 @@ class TestCRUD(unittest.TestCase):
 
     def test_insert_id(self):
         """Test CRUD insert when used ID is given."""
-        object_ = gen_dummy_object("dummyClass", self.doc)
-        id_ = 1
+        object_ = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
+        id_ = "1"
         response_code = None
         try:
             insert_response = crud.insert(
@@ -196,7 +203,7 @@ class TestCRUD(unittest.TestCase):
         objects = list()
         ids = "1,2,3"
         for index in range(len(ids.split(','))):
-            object = gen_dummy_object("dummyClass", self.doc)
+            object = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
             objects.append(object)
         response_code = None
         try:
@@ -210,7 +217,7 @@ class TestCRUD(unittest.TestCase):
         objects = list()
         ids = "1,2,3"
         for index in range(len(ids.split(','))):
-            object = gen_dummy_object("dummyClass", self.doc)
+            object = gen_dummy_object(random.choice(self.doc_collection_classes), self.doc)
             objects.append(object)
         insert_response = crud.insert_multiple(objects_=objects,
                                                session=self.session, id_=ids)
diff --git a/hydrus/tests/test_parser.py b/hydrus/tests/test_parser.py
index c3e0a70..2b8cc5c 100644
--- a/hydrus/tests/test_parser.py
+++ b/hydrus/tests/test_parser.py
@@ -67,7 +67,6 @@ class TestParser(unittest.TestCase):
         """Test if the variables can be removed from the path"""
         path = "A/B/C/{id}"
         result = openapi_parser.sanitise_path(path)
-        assert result == 'A/B/C'
         assert isinstance(result, str)
 
     def test_allow_parameter(self):
@@ -86,6 +85,24 @@ class TestParser(unittest.TestCase):
         result = openapi_parser.parse(self.doc)
         assert isinstance(result, str)
 
+    def test_check_collection(self):
+        """Test if collections are being identified properly"""
+        schema_block = {
+            'type': 'array', 'items': {
+                '$ref': '#/definitions/Pet'}}
+        method = "/Pet"
+        result = openapi_parser.check_collection(schema_block, method)
+        assert isinstance(result, bool)
+        assert result
+
+    def test_check_collection_false(self):
+        "Test if non collections are identified"
+        schema = {'$ref': '#/definitions/User'}
+        method = "/Pet"
+        result = openapi_parser.check_collection(schema, method)
+        assert isinstance(result, bool)
+        assert result == False
+
 
 if __name__ == '__main__':
     print("Starting tests ..")