Simple Crud Api With Django Rest Framework

Overview

SIMPLE CRUD API WITH DJANGO REST FRAMEWORK

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Requirements

  • Python 3.6
  • Django 3.1
  • Django REST Framework

Installation

After you cloned the repository, you want to create a virtual environment, so you have a clean python installation. You can do this by running the command

python -m venv env

After this, it is necessary to activate the virtual environment, you can get more information about this here

You can install all the required dependencies by running

pip install -r requirements.txt

Structure

In a RESTful API, endpoints (URLs) define the structure of the API and how end users access data from our application using the HTTP methods - GET, POST, PUT, DELETE. Endpoints should be logically organized around collections and elements, both of which are resources.

In our case, we have one single resource, movies, so we will use the following URLS - /movies/ and /movies/ for collections and elements, respectively:

Endpoint HTTP Method CRUD Method Result
movies GET READ Get all movies
movies/:id GET READ Get a single movie
movies POST CREATE Create a new movie
movies/:id PUT UPDATE Update a movie
movies/:id DELETE DELETE Delete a movie

Use

We can test the API using curl or httpie, or we can use Postman

Httpie is a user-friendly http client that's written in Python. Let's try and install that.

You can install httpie using pip:

pip install httpie

First, we have to start up Django's development server.

python manage.py runserver

Only authenticated users can use the API services, for that reason if we try this:

http  http://127.0.0.1:8000/api/v1/movies/

we get:

{
    "detail": "Authentication credentials were not provided."
}

Instead, if we try to access with credentials:

http http://127.0.0.1:8000/api/v1/movies/3 "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjE2MjA4Mjk1LCJqdGkiOiI4NGNhZmMzMmFiZDA0MDQ2YjZhMzFhZjJjMmRiNjUyYyIsInVzZXJfaWQiOjJ9.NJrs-sXnghAwcMsIWyCvE2RuGcQ3Hiu5p3vBmLkHSvM"

we get the movie with id = 3

{  "title":  "Avengers",  "genre":  "Superheroes",  "year":  2012,  "creator":  "admin"  }

Create users and Tokens

First we need to create a user, so we can log in

http POST http://127.0.0.1:8000/api/v1/auth/register/ email="[email protected]" username="USERNAME" password1="PASSWORD" password2="PASSWORD"

After we create an account we can use those credentials to get a token

To get a token first we need to request

http http://127.0.0.1:8000/api/v1/auth/token/ username="username" password="password"

after that, we get the token

{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxNjI5MjMyMSwianRpIjoiNGNkODA3YTlkMmMxNDA2NWFhMzNhYzMxOTgyMzhkZTgiLCJ1c2VyX2lkIjozfQ.hP1wPOPvaPo2DYTC9M1AuOSogdRL_mGP30CHsbpf4zA",
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjE2MjA2MjIxLCJqdGkiOiJjNTNlNThmYjE4N2Q0YWY2YTE5MGNiMzhlNjU5ZmI0NSIsInVzZXJfaWQiOjN9.Csz-SgXoItUbT3RgB3zXhjA2DAv77hpYjqlgEMNAHps"
}

We got two tokens, the access token will be used to authenticated all the requests we need to make, this access token will expire after some time. We can use the refresh token to request a need access token.

requesting new access token

http http://127.0.0.1:8000/api/v1/auth/token/refresh/ refresh="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYxNjI5MjMyMSwianRpIjoiNGNkODA3YTlkMmMxNDA2NWFhMzNhYzMxOTgyMzhkZTgiLCJ1c2VyX2lkIjozfQ.hP1wPOPvaPo2DYTC9M1AuOSogdRL_mGP30CHsbpf4zA"

and we will get a new access token

{
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjE2MjA4Mjk1LCJqdGkiOiI4NGNhZmMzMmFiZDA0MDQ2YjZhMzFhZjJjMmRiNjUyYyIsInVzZXJfaWQiOjJ9.NJrs-sXnghAwcMsIWyCvE2RuGcQ3Hiu5p3vBmLkHSvM"
}

The API has some restrictions:

  • The movies are always associated with a creator (user who created it).
  • Only authenticated users may create and see movies.
  • Only the creator of a movie may update or delete it.
  • The API doesn't allow unauthenticated requests.

Commands

Get all movies
http http://127.0.0.1:8000/api/v1/movies/ "Authorization: Bearer {YOUR_TOKEN}" 
Get a single movie
http GET http://127.0.0.1:8000/api/v1/movies/{movie_id}/ "Authorization: Bearer {YOUR_TOKEN}" 
Create a new movie
http POST http://127.0.0.1:8000/api/v1/movies/ "Authorization: Bearer {YOUR_TOKEN}" title="Ant Man and The Wasp" genre="Action" year=2018 
Full update a movie
http PUT http://127.0.0.1:8000/api/v1/movies/{movie_id}/ "Authorization: Bearer {YOUR_TOKEN}" title="AntMan and The Wasp" genre="Action" year=2018
Partial update a movie
http PATCH http://127.0.0.1:8000/api/v1/movies/{movie_id}/ "Authorization: Bearer {YOUR_TOKEN}" title="AntMan and The Wasp" 
Delete a movie
http DELETE http://127.0.0.1:8000/api/v1/movies/{movie_id}/ "Authorization: Bearer {YOUR_TOKEN}"

Pagination

The API supports pagination, by default responses have a page_size=10 but if you want change that you can pass through params page_size={your_page_size_number}

http http://127.0.0.1:8000/api/v1/movies/?page=1 "Authorization: Bearer {YOUR_TOKEN}"
http http://127.0.0.1:8000/api/v1/movies/?page=3 "Authorization: Bearer {YOUR_TOKEN}"
http http://127.0.0.1:8000/api/v1/movies/?page=3&page_size=15 "Authorization: Bearer {YOUR_TOKEN}"

Filters

The API supports filtering, you can filter by the attributes of a movie like this

http http://127.0.0.1:8000/api/v1/movies/?title="AntMan" "Authorization: Bearer {YOUR_TOKEN}"
http http://127.0.0.1:8000/api/v1/movies/?year=2020 "Authorization: Bearer {YOUR_TOKEN}"
http http://127.0.0.1:8000/api/v1/movies/?year__gt=2019&year__lt=2022 "Authorization: Bearer {YOUR_TOKEN}"
http http://127.0.0.1:8000/api/v1/movies/?genre="Action" "Authorization: Bearer {YOUR_TOKEN}"
http http://127.0.0.1:8000/api/v1/movies/?creator__username="myUsername" "Authorization: Bearer {YOUR_TOKEN}"

You can also combine multiples filters like so

http http://127.0.0.1:8000/api/v1/movies/?title="AntMan"&year=2020 "Authorization: Bearer {YOUR_TOKEN}"
http http://127.0.0.1:8000/api/v1/movies/?year__gt=2019&year__lt=2022&genre="Action" "Authorization: Bearer {YOUR_TOKEN}"
Owner
kibet hillary
Watch, Follow, Ask And Learn
kibet hillary
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 01, 2023
A lightweight REST miniframework for Python.

restless A lightweight REST miniframework for Python. Documentation is at https://restless.readthedocs.io/. Works great with Django, Flask, Pyramid, T

Daniel Lindsley 824 Nov 20, 2022
Async Python 3.6+ web server/framework | Build fast. Run fast.

Sanic | Build fast. Run fast. Build Docs Package Support Stats Sanic is a Python 3.6+ web server and web framework that's written to go fast. It allow

Sanic Community Organization 16.7k Dec 28, 2022
Document Web APIs made with Django Rest Framework

DRF Docs Document Web APIs made with Django Rest Framework. View Demo Contributors Wanted: Do you like this project? Using it? Let's make it better! S

Manos Konstantinidis 626 Nov 20, 2022
A Django-powered API with various utility apps / endpoints.

A Django-powered API Includes various utility apps / endpoints. Demos These web apps provide a frontend to the APIs in this project. Issue API Explore

Shemar Lindie 0 Sep 13, 2021
Dropdown population implementation for Django REST Framework

drf-dropdown Dropdown population implementation for Django REST Framework Usage Add DropdownView to API URL # urls.py import dropdown urlpatterns = [

Preeti Yuankrathok 4 Dec 06, 2022
Sanic-RESTPlus is an extension for Sanic that adds support for quickly building REST APIs.

Sanic RestPlus Sanic-RESTPlus is an extension for Sanic that adds support for quickly building REST APIs. Sanic-RESTPlus encourages best practices wit

Ashley Sommer 106 Oct 14, 2022
Simplified REST API to get stickers from Snap

Snap Sticker kit REST API Simplified REST API to get stickers from Snap đź’» Instructions Search stickers Request: url = "https://sticker-kit-horizon733

Dishant Gandhi 1 Jan 05, 2022
Simple Crud Api With Django Rest Framework

SIMPLE CRUD API WITH DJANGO REST FRAMEWORK Django REST framework is a powerful and flexible toolkit for building Web APIs. Requirements Python 3.6 Dja

kibet hillary 1 May 03, 2022
Python bindings for Podman's RESTful API

podman-py This python package is a library of bindings to use the RESTful API of Podman. It is currently under development and contributors are welcom

Containers 142 Jan 06, 2023
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.3k Jan 04, 2023
One package to access multiple different data sources through their respective API platforms.

BESTLab Platform One package to access multiple different data sources through their respective API platforms. Usage HOBO Platform See hobo_example.py

Wei 1 Nov 16, 2021
A RESTful whois

whois-rest A RESTful whois. Installation $ pip install poetry $ poetry install $ uvicorn app:app INFO: Started server process [64616] INFO: W

Manabu Niseki 4 Feb 19, 2022
Recursive Serialization for Django REST framework

djangorestframework-recursive Overview Recursive Serialization for Django REST framework This package provides a RecursiveField that enables you to se

336 Dec 28, 2022
BloodDonors: Built using Django REST Framework for the API backend and React for the frontend

BloodDonors By Daniel Yuan, Alex Tian, Aaron Pan, Jennifer Yuan As the pandemic raged, one of the side effects was an urgent shortage of blood donatio

Daniel Yuan 1 Oct 24, 2021
Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)

django-cors-headers A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django a

Adam Johnson 4.8k Jan 05, 2023
Django REST API with React BoilerPlate

This is a setup of Authentication and Registration Integrated with React.js inside the Django Templates for web apps

Faisal Nazik 91 Dec 30, 2022
Estudo e desenvolvimento de uma API REST

Estudo e desenvolvimento de uma API REST 🧑‍💻 Tecnologias Esse projeto utilizará as seguintes tecnologias: Git Python Flask DBeaver Vscode SQLite 🎯

Deusimar 7 May 30, 2022
A Django api to display items and their current up-to-date prices from different online retailers in one platform.

A Django api to display items and their current up-to-date prices from different online retailers in one platform. Utilizing scrapy to periodically scrape the latest prices from different online reta

Kennedy Ngugi Mwaura 1 Nov 05, 2021