PYTHON DJANGO를 사용하여 REST API 구축 - 4부 🐍

목차
* 🤓 INTRO
* 🔗 URLS
* 👨🏻‍💻 SERIALIZERS
* 👁‍🗨 VIEWS
* 🗺 MAP URL
* 1️⃣ GET SPECIFIC RECORD
* 📣 OUTRO
* 🙏 THANK YOU

🤓 소개

Hello, dear hackers! Welcome to yet another blog article on "Building the REST API with Python Django". I really appreciate your interest in these kinds of articles, and I am really happy that I can help you learn something new.

If you missed the previous article, check it out:

Everything I do in this article and upcoming articles will be pushed to the repository on my GitHub:

데블라자95 / PythonDjango튜토리얼


"Python Django를 사용하여 REST API 빌드" 시리즈에 관한 Codespresso Dev.to 튜토리얼의 공식 저장소입니다.





PythonDjango튜토리얼


"Python Django를 사용하여 REST API 빌드"시리즈에 관한 Codespresso Dev.to 튜토리얼의 공식 저장소입니다.

프로젝트 실행 방법


  • PostgreSQL 데이터베이스 설정(이름: 회사)
  • settings.py를 편집하고 DATABASES 이름을 회사에 지정합니다
  • .
  • 이 저장소에서 코드를 가져옵니다
  • .
  • PyCharm에서 열기
  • 터미널을 열고 pip install -r requirements.txt를 실행합니다.
  • python manage.py 마이그레이션 실행
  • python manage.py runserver 실행



  • View on GitHub



    오늘날 우리는 API에서 모든 데이터를 GET하고 레코드 ID로 특정 레코드를 GET하는 방법을 작성하고 있습니다.

    를 통해 저에게 연락해 주십시오. 또는

    시작하자! 🚀

    🔗 URL

    We already have our urls.py inside our company folder. But what we want to achieve is to make our API URLs map as follow:

  • http://127.0.0.1:8000/api/ - 기본 URL

  • http://127.0.0.1:8000/api/employee/ - 데이터베이스의 모든 직원에 대한 데이터 반환

  • http://127.0.0.1:8000/api/employee/:id - 특정 직원 조작

  • http://127.0.0.1:8000/api/sector/ - 데이터베이스의 모든 섹터에 대한 데이터 반환

  • http://127.0.0.1:8000/api/sector/:id - 특정 섹터 조작

  • http://127.0.0.1:8000/api/project/ - 데이터베이스의 모든 프로젝트에 대한 데이터 반환

  • http://127.0.0.1:8000/api/project/:id - 특정 섹터 조작

  • 모든 경로가/api/...에 매핑되도록 하기 위해 API 폴더 내에 또 다른 파일을 만들고 이름을 urls.py로 지정합니다.



    이 파일을 진행하기 전에 직렬 변환기와 보기를 만들어야 합니다.

    👨🏻‍💻 시리얼라이저

    Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML, or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

    The serializers in the REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.

    In our serializers.py add the following code (note that I omitted the code regarding UserSerializer and GroupSerializer):

    from company.API.models import Employee
    
    class EmployeeSerializer(serializers.ModelSerializer):
        class Meta:
            model = Employee
            fields = '__all__'
    

    This means that we will serialize our Model Employee and include all the fields that our model offers.

    👁‍🗨 조회수

    Each view we create will handle specific logic and will map the response with the specific route. Let's create our first view, which will get all the data regarding employees.

    In your views.py file add the following code:

    from company.API.serializers import UserSerializer, GroupSerializer, EmployeeSerializer
    from company.API.models import Employee
    from rest_framework.response import Response
    from rest_framework.views import APIView
    
    
    class EmployeeList(APIView):
        """
        List all employees
        """
        def get(self, request, format=None):
            employees = Employee.objects.all()
            serializer = EmployeeSerializer(employees, many=True)
            return Response(serializer.data)
    

    🗺 지도 URL

    Before we add some code to the newly created urls.py, go to the urls.py file inside the company folder, and in the urlpatterns block add the following code:

    path('api/', include('company.API.urls'))
    
    This part of the code will consider the http://127.0.0.1:8000/api/ - 기본 URL - 그러나 해당 경로는 새로 생성된 urls.py 내부의 모든 경로를 매핑합니다.

    이제 Employee serializer와 Employee View가 있으므로 응답 데이터를 매핑할 특정 엔드포인트가 필요합니다.

    새로 생성된 urls.py에서 다음 코드를 추가합니다.

    from . import views
    from django.urls import path
    from rest_framework.urlpatterns import format_suffix_patterns
    
    urlpatterns = [
        path('employee/', views.EmployeeList.as_view(), name="employees")
    ]
    
    urlpatterns = format_suffix_patterns(urlpatterns)
    


    이렇게 하면 EmployeeList 보기 응답이 http://127.0.0.1:8000/api/employee/에 매핑됩니다.

    이제 서버에서 데이터를 가져올 준비가 되었습니다(진행하기 전에 관리자 패널을 사용하여 직원에 대한 일부 데이터를 추가하십시오).

    다음 명령을 실행합니다.

    python manage.py runserver
    


    here을 클릭하여 브라우저에서 결과를 보거나 URL 표시줄에 수동으로 입력하십시오http://127.0.0.1:8000/api/employee/.

    데이터베이스에 레코드가 하나뿐이므로 응답은 다음과 같습니다.



    축하합니다! 🎉 첫 번째 GET 요청을 만들었고 Postman을 사용하여 요청을 보낼 수도 있습니다. 지금은 브라우저를 사용하겠습니다.

    1️⃣ 구체적인 기록 얻기

    Similarly, when we want to get the specific record by the unique identifier, we define our view that we will name EmployeeDetails, and after that, we map our view to the specific URL.

    Here is the view for getting specific Employee record by the unique identifier

    class EmployeeDetails(APIView):
        """Retrieve an employee instance"""
    
        def get_object(self, pk):
            try:
                return Employee.objects.get(pk=pk)
            except:
                raise Http404
    
        def get(self, request, pk, format=None):
            employee = self.get_object(pk)
            serializer = EmployeeSerializer(employee)
            return Response(serializer.data)
    

    As you can see, we are using get_object function where we pass the primary key of an instance we are requesting. We have a try-except block of code, where we determine if such an instance exists, or if it does not, we raise an error. An Http404 error is imported as from django.http import Http404 ;

    Now, we should map our URL, add the following code to the urlpatterns inside the newly created urls.py file.

    path('employee/<slug:pk>', views.EmployeeDetails.as_view(), name="employee")
    

    Ok, we should be ready to retrieve the specific data for a single Employee instance. First, you need a primary key, if you execute http://127.0.0.1:8000/api/employee/ you will see that each employee has an employee_id attribute, copy one of the employee_ids and execute this route https://127.0.0.1:8000/api/employee/paste_your_employee_id_here you should GET a single instance with the specific employee_id you requested.

    Here is mine 👽



    📣 아웃트로

    So, we created views for getting all employees' data and for getting a single employee data. The logic is the same for the Project and Sector model. I encourage you to try, and write those views, serializers and urls by yourself, but If you get stuck, you can always look for the solution on my GitHub. In the next article, we will create the POST and PUT methods.

    🙏 읽어주셔서 감사합니다!

    Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me!

    ☕ SUPPORT ME AND KEEP ME FOCUSED!


    즐거운 해킹 시간 되세요! 😊

    좋은 웹페이지 즐겨찾기