├── api_app ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── tests.py ├── admin.py ├── apps.py ├── urls.py ├── models.py ├── serializers.py └── views.py ├── shopping_cart ├── __init__.py ├── asgi.py ├── wsgi.py ├── urls.py └── settings.py ├── requirements.txt ├── manage.py ├── README.md └── .gitignore /api_app/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /shopping_cart/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /api_app/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /api_app/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asgiref==3.4.1 2 | Django==3.2.6 3 | djangorestframework==3.12.4 4 | pytz==2021.1 5 | sqlparse==0.4.1 -------------------------------------------------------------------------------- /api_app/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from .models import CartItem 3 | # Register your models here. 4 | admin.site.register(CartItem) 5 | -------------------------------------------------------------------------------- /api_app/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class ApiAppConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'api_app' 7 | -------------------------------------------------------------------------------- /api_app/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from .views import CartItemViews 3 | 4 | 5 | urlpatterns = [ 6 | path('cart-items/', CartItemViews.as_view()), 7 | path('cart-items/', CartItemViews.as_view()) 8 | ] 9 | -------------------------------------------------------------------------------- /api_app/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class CartItem(models.Model): 5 | product_name = models.CharField(max_length=200) 6 | product_price = models.FloatField() 7 | product_quantity = models.PositiveIntegerField() 8 | -------------------------------------------------------------------------------- /api_app/serializers.py: -------------------------------------------------------------------------------- 1 | from rest_framework import serializers 2 | from .models import CartItem 3 | 4 | 5 | class CartItemSerializer(serializers.ModelSerializer): 6 | product_name = serializers.CharField(max_length=200) 7 | product_price = serializers.FloatField() 8 | product_quantity = serializers.IntegerField(required=False, default=1) 9 | 10 | class Meta: 11 | model = CartItem 12 | fields = ('__all__') 13 | -------------------------------------------------------------------------------- /shopping_cart/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for shopping_cart project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shopping_cart.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /shopping_cart/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for shopping_cart project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shopping_cart.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /api_app/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 3.2.6 on 2021-08-24 11:14 2 | 3 | from django.db import migrations, models 4 | 5 | 6 | class Migration(migrations.Migration): 7 | 8 | initial = True 9 | 10 | dependencies = [ 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='CartItem', 16 | fields=[ 17 | ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('product_name', models.CharField(max_length=200)), 19 | ('product_price', models.FloatField()), 20 | ('product_quantity', models.PositiveIntegerField()), 21 | ], 22 | ), 23 | ] 24 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shopping_cart.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # creating-a-rest-api-with-django-rest-framework 2 | Accompanying code for this article https://stackabuse.com/creating-a-rest-api-with-django-rest-framework/ 3 | 4 | 5 | ## Instructions to run this project locally: 6 | 7 | 1. Clone repository: 8 | 9 | ```console 10 | $ git clone https://github.com/StackAbuse/creating-a-rest-api-with-django-rest-framework.git 11 | ``` 12 | 13 | 2. Install requirements: 14 | 15 | ```console 16 | $ pip install -r requirements.txt 17 | ``` 18 | 19 | 3. Set up DB: 20 | 21 | ```console 22 | $ python manage.py makemigrations 23 | $ python manage.py migrate 24 | ``` 25 | 26 | 4. Run the app: 27 | 28 | ```console 29 | $ python manage.py runserver 30 | ``` 31 | 32 | Thanks for reading. 33 | 34 | -------------------------------------------------------------------------------- /shopping_cart/urls.py: -------------------------------------------------------------------------------- 1 | """shopping_cart URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | 19 | urlpatterns = [ 20 | path('admin/', admin.site.urls), 21 | path('api/', include('api_app.urls')), 22 | ] 23 | -------------------------------------------------------------------------------- /api_app/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import get_object_or_404 2 | from rest_framework.views import APIView 3 | from rest_framework.response import Response 4 | from rest_framework import status 5 | from .serializers import CartItemSerializer 6 | from .models import CartItem 7 | 8 | 9 | class CartItemViews(APIView): 10 | 11 | def get(self, request, id=None): 12 | if id: 13 | item = CartItem.objects.get(id=id) 14 | serializer = CartItemSerializer(item) 15 | return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) 16 | 17 | items = CartItem.objects.all() 18 | serializer = CartItemSerializer(items, many=True) 19 | return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) 20 | 21 | def post(self, request): 22 | serializer = CartItemSerializer(data=request.data) 23 | if serializer.is_valid(): 24 | serializer.save() 25 | return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) 26 | else: 27 | return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) 28 | 29 | def patch(self, request, id=None): 30 | item = CartItem.objects.get(id=id) 31 | serializer = CartItemSerializer(item, data=request.data, partial=True) 32 | if serializer.is_valid(): 33 | serializer.save() 34 | return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) 35 | else: 36 | return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) 37 | 38 | def delete(self, request, id=None): 39 | item = get_object_or_404(CartItem, id=id) 40 | item.delete() 41 | return Response({"status": "success", "data": "Item Deleted"}) 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /shopping_cart/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for shopping_cart project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.6. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-gv$5)d&$nmzwt$+u^ym25i54womkjm9-u-cv!*l9v2m#x3pg7+' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'rest_framework', 41 | 'api_app', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'shopping_cart.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'shopping_cart.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | --------------------------------------------------------------------------------