Creating a Rest API with Django in Python: Chapter 14 – Creating a Post

Posted by

Django Pythonで作るRest API

Pythonで作るRest API – Create Post

Django is a high-level Python web framework that promotes rapid development and clean, pragmatic design. It allows developers to build web applications quickly and efficiently. In this tutorial, we will learn how to create a REST API using Django and Python.

Step 1: Set Up Django Project

First, we need to set up a new Django project. You can do this by running the following command in your terminal:

django-admin startproject myproject

Step 2: Create a Django App

Next, we need to create a new Django app within our project. Run the following command in your terminal:

python manage.py startapp myapp

Step 3: Define Models

We need to define our data models for our API. In this case, we will create a model for posts. Inside the models.py file in our app directory, add the following code:


from django.db import models

class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()

Step 4: Create Serializers

Next, we need to create serializers for our models. Create a new file called serializers.py in your app directory and add the following code:


from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'content']

Step 5: Create Views

Now, we need to create views for our API. Create a new file called views.py in your app directory and add the following code:


from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer

class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer

Step 6: Register Views

Finally, we need to register our views in the urls.py file in our app directory. Add the following code:


from rest_framework import routers
from .views import PostViewSet

router = routers.DefaultRouter()
router.register(r'posts', PostViewSet)

That’s it! We have now created a REST API for creating posts using Django and Python. Happy coding!