Home > Software engineering >  Trying to create simple API with Django Rest Framework
Trying to create simple API with Django Rest Framework

Time:07-17

I think something is wrong with imports. the error is ImproperlyConfigured: The included URLconf 'API_practice.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Coded along with tutorial https://medium.com/swlh/build-your-first-rest-api-with-django-rest-framework-e394e39a482c coded everything line by line doing the same coding but not helping. Here is some of my code.

I added my installed apps in settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'my_api.apps.MyApiConfig',
]

created serializer.py:

from rest_framework import serializers
from .model import Hero

class HeroSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Hero
        fields = ('name', 'alias')

views.py:

from django.shortcuts import render
from rest_framework import viewsets
from django.views import View
from django.http import HttpResponse
from .serializers import HeroSerializer
from .models import Hero
# Create your views here.

class HeroViewSet(viewsets.ModelViewSet):
    queryset = Hero.objects.all().order_by('name')
    serializer_class = HeroSerializer

class IndexView(View):
    def get(self, request):
        return HttpResponse('This is Home Page!')

my_api/urls.py (urls of my app):

from django.urls import include, path
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'heroes', views.HeroViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    path("home/", views.IndexView.as_view, name="home")]

my_API/urls.py (urls of my project):

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('my_api.urls'))]

models.py:

from django.db import models

# Create your models here.

class Hero(models.Model):
    name = models.CharField(max_length=50)
    alias = models.CharField(max_length=50)
    
    def __str__(self):
        return self.name

CodePudding user response:

You are missing "s" in models of from .model import Hero in serializers.

  • Related