Package: django-rest-mock
Django REST MockMock Express server generated based on your views, that can come in handy when developing REST APIs with Django.Typically, the Django developer can first create all the views with docstrings and pass on the project to the front-end developer who can work with the mock server which outputs what is already expected. This allows frontend devs to work with a stable and predictable API.RequirementsRequires Django 1.11 or later and Node.js.Note that this requires views to be Class-based Views.InstallationUsing pip:$ pip install django-rest-mockThen includerest_mock_serverinto yourINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'rest_mock_server',
    ...
)UsageAfter including docstrings for the views you wish to generate endpoints for, you may run the following commandsGenerates an ExpressJS file:$ python manage.py genmockserverStarts an ExpressJS server (it will generate an ExpressJS file if necessary):$ python manage.py startmockserverSyntaxBasic endpoint:class SomeView(APIView):
    """
    URL: /some-view/
    """

    def get(self, request, *args, **kwargs):
        """
        ```
        {
            "data": "Hello, world!"
        }
        ```
        """
        passRESTful endpoint with list & instances:class ResourceListView(ListCreateAPIView):
    """
    URL: /resource/__key
    """

    def post(self, request, *args, **kwargs):
        """
        ```
        {
            "__options": {
                    "excludeKey": true
            },
        }
        ```
        """
        pass

class ResourceView(RetrieveUpdateDestroyAPIView):
    """
    URL: /resource/__key
    """

    def get(self, request, *args, **kwargs):
        """
        ```
        {
            "__key": "<id:int>",
            "__key_position": "url",
            "__mockcount": 5,
            "__options": {
                "modifiers": ["patch", "put", "delete"],
                "excludeKey": false
            },
            "id": "<int>",
            "name": "<name>",
            "complexStructure": [
                {
                    "link": "<int::10>",
                    "url": "<uri>",
                    "related_user": {
                        "id": "<int:1:5>",
                        "hash": "<sha256>"
                    }
                }
            ]
        }
        ```
        """
        pass

    def put(self, request, *args, **kwargs):
        """We won't need to specify any response here"""
        pass

    def patch(self, request, *args, **kwargs):
        """We won't need to specify any response here"""
        pass

    def delete(self, request, *args, **kwargs):
        """We won't need to specify any response here"""
        passWhen creating fixtures for a resource (CRUD), you only need to work with the instance endpoint, inDjango REST framework, it’s typically the endpoint that requires a unique ID - e.g./some-resource/<pk>You need to specify__keyin the url and also in the response as above. The value follows the following syntax<name-of-unique-key:data-type>.
You will also need to specify the position of the key: eitherurlorquery. If it isurl, it exists as a URL param, andquerymeans that the key should be found in query string.__mockcount: (defaults to 1) Represents the number of instances of this fixture to create__options: Possible options related to this endpoint:modifiers: a list of modifier methods allowed for this resource. If you don’t specify a method, that method won’t be allowed for that endpointexcludeKey: this can be specified to exclude a method from matching__keyin the url. E.g. for the POST method for/resource/, you might want to exclude itThe syntax for fake data is as follows:<fakedatatype:min:max>fakedatatypeis any attribute that can be generated byFakermin: for numbers, it will only generated random numbers that are at leastminor greater. For strings, this will be the first index it will slice frommax: for numbers, it will only generated random numbers that are at mostmaxor smaller. For strings, this will be the last indexSpecial Characters^: Putting a caret in front of the variable like “<^int:500:1000>” will generate only unique numbers between 500 to 1000POST requests will not create new instances, but PUT, PATCH and DELETE will work as expected on the resources.
The resources are reset everytime the server is restarted.Meta-KeysAs you have probably seen in the examples above, there are special keys prefixed with double-underscores such as__key. These are meta-keys which will be used to grant special properties to the mock responses.__key: Represents the primary key/unique identifier of an instance__key_position: Where the__keyshould be located in the url - there are only two options “url” or “query”.url: The key should be within the main url such as/api/example/__keyquery: They key should be within the params such asapi/example?id[str]=__key__mockcount: The number of instances to create. Note that if__keyis specified, an endpoint will be created that lists all the individual instances. However, if no__keyis specified, then the endpoint will just return an array of N instances where N is specified in__mockcount__relationships: Relationships dictate simple relationships between items in the mock response. The syntax is always “<source__relationship__target>”count: It would be best illustrated with an example:{
    "__relationships": [
        "user_count__count__users",
    ],
    "user_count": 20,
    "users": [
        {
            "id": "<int::50>",
            "user": "<name>"
        }
    ]
}If you want to specify a source value without displaying it in the eventual endpoint, you may use the hidden syntax with a double-dash:{
    "__relationships": [
        "--user_count__count__users",
    ],
    "--user_count": 20,
    "users": [
        {
            "id": "<int::50>",
            "user": "<name>"
        }
    ]
}__options: Possible options related to this endpoint are as followsmodifiers: a list of modifier methods allowed for this resource. If you don’t specify a method, that method won’t be allowed for that endpointexcludeKey: this can be specified to exclude a method from matching__keyin the url. E.g. for the POST method for/resource/, you might want to exclude itFixturesMore often than not, you will need to load fixtures to populate the mock endpoints.We can load fixtures during generation by specifying the--fixturesflag:python manage.py genmockserver--fixturesdataNote that the folders must be direct parents. All files with.jsonextension will be taken into account.The syntax for that will be: “<key__from__filename>”If a file calledusers.jsonwas loaded, then you can do:{
    "id": "<id__from__users>",
    "full_name": "<first_name__from__users> <last_name__from__users>",
    "contact": "<contact__from__users>"
}The JSON files must follow Django’s format of JSON fixtures and the fields must include the keys used in the mock response. So “id”, “first_name”, “last_name” and “contact” must all exist in the users fields.Advanced Usage with *There may be a situation where you would like to specify the keys in an endpoint and what type of response each key maps to.For example, you might have the following base URL “/api/example” and you would like to have the following key definition:URL: /api/example?id[str]=__key

{
    "__key": "<*id:str>",
    "__key_position": "query",
    "users": [
        {
            "id": "<id__from__users>",
            "name": "<name__from__users>"
        }
    ],
    "burgers": [
        {
            "id": "<id__from__burgers>",
            "burger_type": "<burger__from__burgers>"
        }
    ]
}This will generate an endpoint that allows for two specific keys “/api/example?id=users” and “/api/example?id=burgers”, which will each respond with whatever is defined under them.
Note the asterisk in front of the key which indicates that all non-meta keys will be taken as keys for this endpoint. In this case, our keys are “users” and “burgers”ExampleRefer to the example app for a detailed example.