boomslag-common-api-response


Nameboomslag-common-api-response JSON
Version 1.2.2 PyPI version JSON
download
home_pagehttps://boomslag.com
SummaryStandard APIReponse for Django Rest Framework
upload_time2023-01-04 18:57:15
maintainer
docs_urlNone
authorBoomslag
requires_python
licenseMIT
keywords django djangorestframework common api response boomslag
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            Boomslag Common API Response
============================

Getting Started
****************

To use the Boomslag Django API Response Views package, follow these steps:

#. Step 1. Install the package in your Django project by running the following command:

    
    pip install boomslag-common-api-response


#. Step 2. Add 'api_response' to your Django installed apps in your project's settings.py file:

    
    INSTALLED_APPS = [
        ...
        'boomslag_api_response',
    ]


#. Step 3. In your Django views, import the BaseAPIView class from the package:

    
    from boomslag_api_response.views import BaseAPIView


#. Step 4. Use the BaseAPIView class as the base class for your Django view. You can then use the following methods to send responses to the client:

Helper Functions
================

* `send_response(data=None, status=status.HTTP_200_OK)`: Sends a successful response to the client. The data parameter is optional and can be used to include additional data in the response. The status parameter can be used to specify the HTTP status code of the response.

* `send_error(error, status=status.HTTP_400_BAD_REQUEST)`: Sends an error response to the client. The error parameter is required and should be a string describing the error. The status parameter can be used to specify the HTTP status code of the response.


Example Views
**************

*Here is an example view* that demonstrates how to use the BaseAPIView class:


    class HelloWorldView(BaseAPIView):
        def get(self, request, format=None):
            your_condition_here = True
            if your_condition_here:
                dict = {'message':'Hello World!'}
                return self.send_response(dict)
            else:
                error_message = 'This is a custom error message.'
                return self.send_error(error_message)


*Here is an example view* that demonstrates how to use the BaseAPIView class with a custom success status code:
    

    class HelloWorldView(BaseAPIView):
        def get(self, request, format=None):
            your_condition_here = True
            if your_condition_here:
                dict = {'message':'Hello World!'}
                return self.send_response(dict,status=status.HTTP_201_CREATED)
            else:
                error_message = 'This is a custom error message. I am a String.'
                return self.send_error(error_message)



When the client sends a request with the success parameter set to true, this view will send a successful response with the message "Hello World!". Otherwise, it will send an error response with the message "Hello Errors!".

The response sent to the client will have the following format:

    {
        "success": true,
        "status": "200"
        "data": {
            "message": "Hello World!"
        },
    }

or

    {
        "success": false,
        "status": "400",
        "error": "This is a custom error message. I am a String."
    }

You can then use the success and data fields in the client to determine the outcome of the request and process the response accordingly.


Paginated Views
===============

To use StandardAPIView, simply inherit it in your view class. You can then use the paginate_data method to easily paginate any data object and return the paginated response.

Example Views
**************

*Here is an example view* that demonstrates how to use the StandardAPIView class that returns a paginated response:
    

    class HelloWorldObjectPaginatedView(StandardAPIView):
        def get(self, request, format=None):
            # Retrieve your data object
            data = MyModel.objects.all()

            # Use the paginate_data method to paginate and return the response
            if data:
                return self.paginate_data(data, request, serializer_class=MyDataSerializer, page_size=3, max_page_size=5)
            else:
                return self.send_error('No data found', status=status.HTTP_404_NOT_FOUND)


The response will be a paginated list of courses, with the pagination metadata included in the response. The pagination metadata will include the current page number, the number of results per page, the total number of results, and the total number of pages. 

For example, if there are 10 courses in total and the page size is 3, the response will include metadata indicating that there are a total of 4 pages, with the first page containing the first 3 courses and the second page containing the next 3 courses, and so on. The data for each course will be included in the 'results' field of the response.

Here is an example of what the response might look like:


    {
        "count": 10,
        "next": "http://example.com/api/courses?page=2",
        "previous": null,
        "results": [
        {
            "id": 1,
            "name": "Introduction to Python",
            "description": "Learn the basics of Python programming"
        },
        {
            "id": 2,
            "name": "Advanced Python Techniques",
            "description": "Learn advanced techniques for Python programming"
        },
        {
            "id": 3,
            "name": "Data Science with Python",
            "description": "Learn how to use Python for data analysis and visualization"
        }
        ]
    }

To use the StandardAPIView, you will need to subclass it and override the **'paginate_data'** method. This method should accept the data object that you want to paginate as well as the request object, and it should return a paginated response. 

You can customize the pagination behavior by passing additional arguments to the **'paginate_data'** method, such as the page size and maximum page size.

You can also pass a serializer class to the 'paginate_data' method if you want to serialize the data object before paginating.

    class StandardAPIView(BaseAPIView):
        pagination_class = CustomPagination

        def paginate_data(self, data, request, serializer_class=None, context=None, **kwargs):
            # Create a paginator instance
            paginator = self.pagination_class(**kwargs)

            # Paginate the data object and return the paginated response
            paginated_data = paginator.paginate_data(data, request)
            if serializer_class:
                serializer = serializer_class(paginated_data, many=True, context=context)
                paginated_data = serializer.data

            # Include the count, next, and previous fields in the response
            response = paginator.get_paginated_response(paginated_data)
            response['count'] = paginator.count
            response['next'] = paginator.get_next_link()
            response['previous'] = paginator.get_previous_link()

            return response

Then we can use the StandardAPIView like in the above example:
    
    
    class HelloWorldObjectPaginatedView(StandardAPIView):
        def get(self, request, format=None):
            courses = Courses.objects.all()
            if courses:
                return self.paginate_data(courses, request, CourseSerializer, page_size=3, max_page_size=5)
            else:
                return self.send_error('No data found')


The response to the request made to the HelloWorldObjectPaginatedView would be a paginated JSON object containing a list of serialized course objects. 

The paginated response would include metadata about the pagination, such as the current page, the number of pages, the number of results per page, and the total number of results. The structure of the response would look like this:

    {
        "count": 6,
        "next": "http://example.com/api/courses?page=2",
        "previous": null,
        "results": [
        {
            "id": 1,
            "name": "Course 1",
            "description": "This is the first course",
            "instructor": "John Smith"
        },
        {
            "id": 2,
            "name": "Course 2",
            "description": "This is the second course",
            "instructor": "Jane Doe"
        },
        {
            "id": 3,
            "name": "Course 3",
            "description": "This is the third course",
            "instructor": "Bob Smith"
        }
        ]
    }

            

Raw data

            {
    "_id": null,
    "home_page": "https://boomslag.com",
    "name": "boomslag-common-api-response",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "support@boomslag.com",
    "keywords": "django djangorestframework common api response boomslag",
    "author": "Boomslag",
    "author_email": "mail@boomslag.com",
    "download_url": "https://files.pythonhosted.org/packages/13/5b/d0fdb16149e6ca86cd32457a89eeffab478137a5b080f13d5e3f6fc30a94/boomslag_common_api_response-1.2.2.tar.gz",
    "platform": null,
    "description": "Boomslag Common API Response\r\n============================\r\n\r\nGetting Started\r\n****************\r\n\r\nTo use the Boomslag Django API Response Views package, follow these steps:\r\n\r\n#. Step 1. Install the package in your Django project by running the following command:\r\n\r\n    \r\n    pip install boomslag-common-api-response\r\n\r\n\r\n#. Step 2. Add 'api_response' to your Django installed apps in your project's settings.py file:\r\n\r\n    \r\n    INSTALLED_APPS = [\r\n        ...\r\n        'boomslag_api_response',\r\n    ]\r\n\r\n\r\n#. Step 3. In your Django views, import the BaseAPIView class from the package:\r\n\r\n    \r\n    from boomslag_api_response.views import BaseAPIView\r\n\r\n\r\n#. Step 4. Use the BaseAPIView class as the base class for your Django view. You can then use the following methods to send responses to the client:\r\n\r\nHelper Functions\r\n================\r\n\r\n* `send_response(data=None, status=status.HTTP_200_OK)`: Sends a successful response to the client. The data parameter is optional and can be used to include additional data in the response. The status parameter can be used to specify the HTTP status code of the response.\r\n\r\n* `send_error(error, status=status.HTTP_400_BAD_REQUEST)`: Sends an error response to the client. The error parameter is required and should be a string describing the error. The status parameter can be used to specify the HTTP status code of the response.\r\n\r\n\r\nExample Views\r\n**************\r\n\r\n*Here is an example view* that demonstrates how to use the BaseAPIView class:\r\n\r\n\r\n    class HelloWorldView(BaseAPIView):\r\n        def get(self, request, format=None):\r\n            your_condition_here = True\r\n            if your_condition_here:\r\n                dict = {'message':'Hello World!'}\r\n                return self.send_response(dict)\r\n            else:\r\n                error_message = 'This is a custom error message.'\r\n                return self.send_error(error_message)\r\n\r\n\r\n*Here is an example view* that demonstrates how to use the BaseAPIView class with a custom success status code:\r\n    \r\n\r\n    class HelloWorldView(BaseAPIView):\r\n        def get(self, request, format=None):\r\n            your_condition_here = True\r\n            if your_condition_here:\r\n                dict = {'message':'Hello World!'}\r\n                return self.send_response(dict,status=status.HTTP_201_CREATED)\r\n            else:\r\n                error_message = 'This is a custom error message. I am a String.'\r\n                return self.send_error(error_message)\r\n\r\n\r\n\r\nWhen the client sends a request with the success parameter set to true, this view will send a successful response with the message \"Hello World!\". Otherwise, it will send an error response with the message \"Hello Errors!\".\r\n\r\nThe response sent to the client will have the following format:\r\n\r\n    {\r\n        \"success\": true,\r\n        \"status\": \"200\"\r\n        \"data\": {\r\n            \"message\": \"Hello World!\"\r\n        },\r\n    }\r\n\r\nor\r\n\r\n    {\r\n        \"success\": false,\r\n        \"status\": \"400\",\r\n        \"error\": \"This is a custom error message. I am a String.\"\r\n    }\r\n\r\nYou can then use the success and data fields in the client to determine the outcome of the request and process the response accordingly.\r\n\r\n\r\nPaginated Views\r\n===============\r\n\r\nTo use StandardAPIView, simply inherit it in your view class. You can then use the paginate_data method to easily paginate any data object and return the paginated response.\r\n\r\nExample Views\r\n**************\r\n\r\n*Here is an example view* that demonstrates how to use the StandardAPIView class that returns a paginated response:\r\n    \r\n\r\n    class HelloWorldObjectPaginatedView(StandardAPIView):\r\n        def get(self, request, format=None):\r\n            # Retrieve your data object\r\n            data = MyModel.objects.all()\r\n\r\n            # Use the paginate_data method to paginate and return the response\r\n            if data:\r\n                return self.paginate_data(data, request, serializer_class=MyDataSerializer, page_size=3, max_page_size=5)\r\n            else:\r\n                return self.send_error('No data found', status=status.HTTP_404_NOT_FOUND)\r\n\r\n\r\nThe response will be a paginated list of courses, with the pagination metadata included in the response. The pagination metadata will include the current page number, the number of results per page, the total number of results, and the total number of pages. \r\n\r\nFor example, if there are 10 courses in total and the page size is 3, the response will include metadata indicating that there are a total of 4 pages, with the first page containing the first 3 courses and the second page containing the next 3 courses, and so on. The data for each course will be included in the 'results' field of the response.\r\n\r\nHere is an example of what the response might look like:\r\n\r\n\r\n    {\r\n        \"count\": 10,\r\n        \"next\": \"http://example.com/api/courses?page=2\",\r\n        \"previous\": null,\r\n        \"results\": [\r\n        {\r\n            \"id\": 1,\r\n            \"name\": \"Introduction to Python\",\r\n            \"description\": \"Learn the basics of Python programming\"\r\n        },\r\n        {\r\n            \"id\": 2,\r\n            \"name\": \"Advanced Python Techniques\",\r\n            \"description\": \"Learn advanced techniques for Python programming\"\r\n        },\r\n        {\r\n            \"id\": 3,\r\n            \"name\": \"Data Science with Python\",\r\n            \"description\": \"Learn how to use Python for data analysis and visualization\"\r\n        }\r\n        ]\r\n    }\r\n\r\nTo use the StandardAPIView, you will need to subclass it and override the **'paginate_data'** method. This method should accept the data object that you want to paginate as well as the request object, and it should return a paginated response. \r\n\r\nYou can customize the pagination behavior by passing additional arguments to the **'paginate_data'** method, such as the page size and maximum page size.\r\n\r\nYou can also pass a serializer class to the 'paginate_data' method if you want to serialize the data object before paginating.\r\n\r\n    class StandardAPIView(BaseAPIView):\r\n        pagination_class = CustomPagination\r\n\r\n        def paginate_data(self, data, request, serializer_class=None, context=None, **kwargs):\r\n            # Create a paginator instance\r\n            paginator = self.pagination_class(**kwargs)\r\n\r\n            # Paginate the data object and return the paginated response\r\n            paginated_data = paginator.paginate_data(data, request)\r\n            if serializer_class:\r\n                serializer = serializer_class(paginated_data, many=True, context=context)\r\n                paginated_data = serializer.data\r\n\r\n            # Include the count, next, and previous fields in the response\r\n            response = paginator.get_paginated_response(paginated_data)\r\n            response['count'] = paginator.count\r\n            response['next'] = paginator.get_next_link()\r\n            response['previous'] = paginator.get_previous_link()\r\n\r\n            return response\r\n\r\nThen we can use the StandardAPIView like in the above example:\r\n    \r\n    \r\n    class HelloWorldObjectPaginatedView(StandardAPIView):\r\n        def get(self, request, format=None):\r\n            courses = Courses.objects.all()\r\n            if courses:\r\n                return self.paginate_data(courses, request, CourseSerializer, page_size=3, max_page_size=5)\r\n            else:\r\n                return self.send_error('No data found')\r\n\r\n\r\nThe response to the request made to the HelloWorldObjectPaginatedView would be a paginated JSON object containing a list of serialized course objects. \r\n\r\nThe paginated response would include metadata about the pagination, such as the current page, the number of pages, the number of results per page, and the total number of results. The structure of the response would look like this:\r\n\r\n    {\r\n        \"count\": 6,\r\n        \"next\": \"http://example.com/api/courses?page=2\",\r\n        \"previous\": null,\r\n        \"results\": [\r\n        {\r\n            \"id\": 1,\r\n            \"name\": \"Course 1\",\r\n            \"description\": \"This is the first course\",\r\n            \"instructor\": \"John Smith\"\r\n        },\r\n        {\r\n            \"id\": 2,\r\n            \"name\": \"Course 2\",\r\n            \"description\": \"This is the second course\",\r\n            \"instructor\": \"Jane Doe\"\r\n        },\r\n        {\r\n            \"id\": 3,\r\n            \"name\": \"Course 3\",\r\n            \"description\": \"This is the third course\",\r\n            \"instructor\": \"Bob Smith\"\r\n        }\r\n        ]\r\n    }\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Standard APIReponse for Django Rest Framework",
    "version": "1.2.2",
    "split_keywords": [
        "django",
        "djangorestframework",
        "common",
        "api",
        "response",
        "boomslag"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7bcc68682bd537948809c599d6eced04ea4a2f1ff3684b4c994a88716f4ce045",
                "md5": "c5494525162808e6d20b42557ee08dd6",
                "sha256": "9acf07d72f4b93bdf9a29418032c191e8e24821ae143abf0356d4df623452887"
            },
            "downloads": -1,
            "filename": "boomslag_common_api_response-1.2.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c5494525162808e6d20b42557ee08dd6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 7981,
            "upload_time": "2023-01-04T18:57:13",
            "upload_time_iso_8601": "2023-01-04T18:57:13.817420Z",
            "url": "https://files.pythonhosted.org/packages/7b/cc/68682bd537948809c599d6eced04ea4a2f1ff3684b4c994a88716f4ce045/boomslag_common_api_response-1.2.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "135bd0fdb16149e6ca86cd32457a89eeffab478137a5b080f13d5e3f6fc30a94",
                "md5": "63194b2b7079b6e5756e2ed9143e150a",
                "sha256": "7ec13e10355881b108fa19b783f4c970f35a08288711ade536e26d4cd25e83d4"
            },
            "downloads": -1,
            "filename": "boomslag_common_api_response-1.2.2.tar.gz",
            "has_sig": false,
            "md5_digest": "63194b2b7079b6e5756e2ed9143e150a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 8504,
            "upload_time": "2023-01-04T18:57:15",
            "upload_time_iso_8601": "2023-01-04T18:57:15.176086Z",
            "url": "https://files.pythonhosted.org/packages/13/5b/d0fdb16149e6ca86cd32457a89eeffab478137a5b080f13d5e3f6fc30a94/boomslag_common_api_response-1.2.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-04 18:57:15",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "boomslag-common-api-response"
}
        
Elapsed time: 0.06584s