Estudo de como criar uma api para o gerenciamento de livros usando a django restframework

Overview

Boa parte do projeto foi beaseado nesse vídeo e nesse artigo. Se assim como eu, você entrou agora no mundo BackEnd, recomendo fortemente tais materiais.
Escrevi esse readme com a intenção de revisar o que aprendi e também ajudar aqueles com caminhos similares no mundo tech. Espero que você aprenda algo novo! 👍

API para uma biblioteca

Introdução

A ideia do projeto é que possamos armazenar livros e seus atributos dentro de um banco de dados e realizar as operações de CRUD sem precisar de uma interface gráfica. Assim, outra aplicação poderá se comunicar com a nossa de forma eficiente.
Esse é o conceito de API (Application Programming Interface)

Preparando o ambiente

Aqui temos a receita de bolo pra deixar a sua máquina pronta para levantar um servidor com o django e receber aquele 200 bonito na cara

>python -m venv venv #criando ambiente virtual na sua versao do python
>./venv/Scripts/Activate.ps1 #Ativando o ambiente virtual
>pip install django djangorestframework #instalação local das nossas dependências
>pip install pillow #biblioteca pra lidar com imagens

O lance do ambiente virtual é que todas suas dependências (que no python costumam ser muitas) ficam apenas num diretório específico.
Logo, com uma venv você pode criar projetos que usam versões diferentes da mesma biblioteca sem que haja conflito na hora do import.

Projeto x App

No django cada project pode carregar múltiplos apps, como um projeto site de esportes que pode ter um app para os artigos, outro para rankings etc.
Ainda no terminal usamos os comandos a seguir para criar o project library que vai carregar nosso app books.

>django-admin startproject library . #ponto indica diretório atual
>django-admin startapp books
>python manage.py runserver #pra levantarmos o servidor local com a aplicação

Sua estrutura de pastas deve estar assim:

imagem da estrutura

Para criar as tabelas no banco de dados (Por enquanto Sqlite3) executamos o comando

>python manage.py migrate

Isso evita que a notificação unapplied migrations apareça na próxima vez que você levantar o servidor

imagem unapplied

Criando os modelos e API

No arquivo ./library/settings.py precisamos indicar ao nosso projeto library sobre a existência do app books e também o uso do rest framework. Portanto adicionamos as seguintes linhas sublinhadas

imagem das linhas

Já que nossa API suporta imagens como atributos também sera necessário o seguite acrescimo de codigo em ./library/settings.py

MEDIA_URL = '/media'
 
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Agora em ./library/books/models.py iremos criar nosso modelo com os atributos que um livro deve ter.

from django.db import models
from uuid import uuid4

#funcao pra receber as imagens e gerar endereço
def upload_image_books(instance, filename):
    return f"{instance.id_book}-{filename}"

class Books(models.Model):
    #criando os atributos do livro
    id_book = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=255)
    release_year = models.IntegerField()
    image = models.ImageField(upload_to=upload_image_books, blank=False, null=True)

Serializers e Viewsets

Dentro de ./library/books iremos criar a pasta /api com os arquivos

  • serializers.py
  • viewsets.py

Serializers

from rest_framework import serializers
from books import models

class BooksSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Books
        fields = '__all__' #todos os campos do model id_book, author..

Viewsets

from rest_framework import viewsets
from books.api import serializers
from books import models

class BooksViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.BooksSerializer
    queryset = models.Books.objects.all() #tambem todos os campos do nosso modelo

Criação das rotas

Agora com o viewset e o serializer a única coisa que falta é uma rota. Portanto vamos para ./library/urls.py resolver esse problema

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

from django.conf.urls.static import static
from django.conf import settings

from rest_framework import routers
from books.api import viewsets as booksviewsets
#criando nosso objeto de rota
route = routers.DefaultRouter()
route.register(r'books', booksviewsets.BooksViewSet, basename="Books")

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(route.urls))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Como criamos um modelo novo lá em cima, precisamos avisar e em seguida migrar todos essas novas informações para o banco de dados

>python manage.py makemigrations 
>python manage.py migrate
>python manage.py runserver 

Agora você pode usar um programa como Insomnia para testar os métodos http no link do seu servidor local. 🥰

insomnia

O python facilita bastante coisas para a gente, como os serializers (que convertem objetos para strings na comunicação cliente-servidor) e os verbos http (GET, POST, PUT, DELETE) que de certa forma também vem por padrão. Não me aprofundei neles durante o readme porque também preciso entender melhor como essas coisas funcionam

Getting Started

# Clone repository
git clone https://github.com/Mesheo/Biblioteca-API.git && cd Biblioteca-API

# Create Virtual Environment
python -m venv venv && ./venv/Scripts/Activate.ps1

# Install dependencies
pip install django djangorestframework

# Run Application
python manage.py runserver
Owner
Michel Ledig
I like to make things easier for other people with code.
Michel Ledig
A program that generates discord.py code

discord-py-generator A program that generates discord.py code Setup in cmds.txt file add your user id, client id and bot token you can change the bot

3 Dec 15, 2022
Report-snapchat - Report Snapchat acc with python

report-snapchat Report Snapchat acc Report users on Snapchat about the tool : 4

17 Dec 01, 2022
A pdisk uploader bot written in Python

Pdisk Uploader Bot 🔥 Upload on Pdisk by Url, File and also by direct forward post from other channel... Features Post to Post Conversion Url Upload D

Paritosh Kumar 33 Oct 21, 2022
A Discord Bot created using Pycord!

Hey, I am Slash Bot. A Bot which works with Slash Commands! Prerequisites Python 3+ Check out. the requirements.txt and install all the pakages. Insta

Saumya Patel 1 Nov 29, 2021
NiceHash Python Library and Command Line Rest API

NiceHash Python Library and Command Line Rest API Requirements / Modules pip install requests Required data and where to get it Following data is nee

Ashlin Darius Govindasamy 2 Jan 02, 2022
A script that writes automatic instagram comments under a post

Send automatic messages under a post on instagram Instagram will rate limit you after some time. From there on you can only post 1 comment every 40 se

Maximilian Freitag 3 Apr 28, 2022
A Python implementation of a Youtube Subscription manager & feed viewer, also does thumbnails

BUILDING Building requires python3.10, and the build package, which can be installed via pip: python3.10 -m pip install build To install, run python3.

2 Feb 28, 2022
AWS DeepRacer Free Student Workshop: Run faster by using your custom waypoints

AWS DeepRacer Free Student Workshop: Run faster by using your custom waypoints Reward Function Template for waypoints def reward_function(params):

Yuen Cheuk Lam 88 Nov 27, 2022
CRUD database for python discord bot developers that stores data on discord text channels

Discord Database A CRUD (Create Read Update Delete) database for python Discord bot developers. All data is stored in key-value pairs directly on disc

Ankush Singh 7 Oct 22, 2022
Google Sheets Python API

Google Spreadsheets Python API v4 Simple interface for working with Google Sheets. Features: Open a spreadsheet by title, key or url. Read, write, and

Anton Burnashev 6.2k Dec 30, 2022
基于nonebot2开发的群管机器人qbot,支持上传并运行python代码以及一些基础管理功能

nonebot2-Eleina 基于nonebot2开发的群管机器人qbot,支持上传并运行python代码以及一些基础管理功能 Readme 环境:python3.7.3+,go-cqhttp 安装及配置:参见(https://v2.nonebot.dev/guide/installation.h

1 Dec 06, 2022
Huggingface inference with GPU Docker on AWS

This repository contains code to containerize and deploy a GPU docker on AWS for summarization task. Find a detailed blogpost here Youtube Video Versi

Ramsri Goutham Golla 21 Dec 30, 2022
Discord feeder for AIL

ail-feeder-discord Discord feeder for AIL Warning! Automating user accounts is technically against TOS, so use at your own risk! Discord API https://d

ail project 6 Mar 09, 2022
Drop-in Replacement of pychallonge

pychal Pychal is a drop-in replacement of pychallonge with some extra features and support for new Python versions. Pychal provides python bindings fo

ZED 29 Nov 28, 2022
Automatically detect changes made to the official Telegram sites.

🕷 Telegram Web Crawler This project is developed to automatically detect changes made to the official Telegram sites. This is necessary for anticipat

Il'ya 115 Dec 31, 2022
A mood based crypto tracking application.

Crypto Bud - API A mood based crypto tracking application. The main repository is private. I am creating the API before I connect everything to the ma

Krishnasis Mandal 1 Oct 23, 2021
Home Assistant Hilo Integration via HACS

BETA This is a beta release. There will be some bugs, issues, etc. Please bear with us and open issues in the repo. Hilo Hilo integration for Home Ass

66 Dec 23, 2022
The Python SDK for the BattleshAPI game

BattleshAPy The Python SDK for the BattleshAPI game Installation This library will be eventually going on PyPI, but until then, simply clone or downlo

Christopher 0 Apr 18, 2022
twitter bot tha uses tweepy library class to connect to TWITTER API

TWITTER-BOT-tweepy- twitter bot that uses tweepy library class to connect to TWITTER API replies to mentions automatically and follows the tweet.autho

Muziwandile Nkomo 2 Jan 08, 2022
SaltConf21: Adding Workflow Approval to Salt

SaltConf21: Adding Workflow Approval to Salt Running To run the example, install Docker and docker-compose and run the following commands: docker-comp

SSYS Sistemas 4 Nov 24, 2021