Create sample REST API with Tastypie

Create sample rest API with Tastypie

Tastypie is a webservice API framework for Django. It provides a convenient, yet powerful and highly customizable, abstraction for creating REST-style interfaces.

https://django-tastypie.readthedocs.io/en/latest/

We can create REST API with Tastypie in two ways, maybe it is available another way.

At first, I created a project with Django and in this project, I added an app called Movies.
As you know, the command to create a project and create an app is as follows:

1.django-admin startproject myapp .
2.python3 manage.py startapp movies

In order not to get away from the discussion, I go to the main topic.

Now you have to enter the following address in the main file:

1. Create api app

In this method, you can create another app called api, just like making an app called movies, and now in the model of this app (api), add a class of resource type to the Movies model as follows:

#api/models.py
from tastypie.resources import ModelResource
from movies.models import Movie

class MovieResource(ModelResource):
    class Meta:
        queryset = Movie.objects.all()
        resource_name = 'movies'
        excludes = ["created_at"]

2. Create api.py in the Movies app

In this method, you can create api.py in your desired app like the Movies app, and save the same codes above in this file as below:

#Movies/api.py
from tastypie.resources import ModelResource
from movies.models import Movie

class MovieResource(ModelResource):
    class Meta:
        queryset = Movie.objects.all()
        resource_name = 'movies'
        excludes = ["created_at"]

Now you should add the following address in the urls.py file:

path("api/", include(movie_resource.urls))
"""
URL configuration for vidly project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from . import views
from api.models import MovieResource 
#from movies.api import MovieResource

movie_resource = MovieResource()

urlpatterns = [
    path("", views.home),
    path("admin/", admin.site.urls),
    path("movies/", include("movies.urls")),
    path("api/", include(movie_resource.urls))
]

the Django project is available in the following GitHub: https://github.com/hedeshmb/python-vidly

Leave a Reply

Your email address will not be published. Required fields are marked *