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
Signs the target email up to over 1000 different mailing lists to get spammed each day.

Email Bomber Say goodbye to that email Features Signs up to over 1k different mailing lists Written in python so the program is lightweight Easy to us

Loxdr 1 Nov 30, 2021
FUD Keylogger That Reports To Discord

This python script will capture all of the keystrokes within a given time frame and report them to a Discord Server using Webhooks. Instead of the traditional

●┼Waseem Akram••✓⁩ 16 Dec 08, 2022
Exchange indicators & Basic functions for Binance API.

binance-ema Exchange indicators & Basic functions for Binance API. This python library has been written to calculate SMA, EMA, MACD etc. functions wit

Emre MENTEŞE 24 Jan 06, 2023
📷 An Instagram bot written in Python using Selenium on Google Chrome

📷 An Instagram bot written in Python using Selenium on Google Chrome. It will go through posts in hashtag(s) and like and comment on them.

anniedotexe 47 Dec 19, 2022
PyMusic Player is a music player written in python3.

PyMusic Player is a music player written in python3. It harvests r

PythonSerious 2 Jan 30, 2022
Asynchronous and also synchronous non-official QvaPay client for asyncio and Python language.

Asynchronous and also synchronous non-official QvaPay client for asyncio and Python language. This library is still under development, the interface could be changed.

Leynier Gutiérrez González 8 Sep 18, 2021
Python script to scrape users/id/badges/creation-date from a Discord Server Memberlist

Discord Server Badges Scraper - Credits to bytixo he made this Custom Discord Vanity Creator How To Use Install discum 1.2 Open a terminal and execute

apolo 13 Dec 09, 2022
DDoS Script (DDoS Panel) with Multiple Bypass ( Cloudflare UAM,CAPTCHA,BFM,NOSEC / DDoS Guard / Google Shield / V Shield / Amazon / etc.. )

KARMA DDoS DDoS Script (DDoS Panel) with Multiple Bypass ( Cloudflare UAM,CAPTCHA,BFM,NOSEC / DDoS Guard / Google Shield / V Shield / Amazon / etc.. )

Hyuk 256 Jan 02, 2023
Bot-moderator for Telegram group chats

Project title A little info about your project and/ or overview that explains what the project is about. 🌟 Hello everyone! This is the repository of

Maxim Zavalniuk 6 Nov 01, 2022
Notification Reminder Application For Python

Notification-Reminder-Application No matter how well you set up your to-do list and calendar, you aren’t going to get things done unless you have a re

1 Nov 26, 2021
A simple healthcheck wrapper to monitor Kafka.

kafka-healthcheck A simple healthcheck wrapper to monitor Kafka. Kafka Healthcheck is a simple server that provides a singular API endpoint to determi

Rodrigo Nicolas Garcia 3 Oct 17, 2022
PYAW allows you to call assembly from python

PYAW allows you to call assembly from python

2 Dec 13, 2021
Automation that uses Github Actions, Google Drive API, YouTube Data API and youtube-dl together to feed BackJam app with new music

Automation that uses Github Actions, Google Drive API, YouTube Data API and youtube-dl together to feed BackJam app with new music

Antônio Oliveira 1 Nov 21, 2021
Webservice that notifies users on Slack when a change in GitLab concern them.

Gitlab Slack Notifier Webservice that notifies users on Slack when a change in GitLab concern them. Setup Slack Create a Slack app, go to "OAuth & Per

Heuritech 2 Nov 04, 2021
100d002 - Simple program to calculate the tip amount and split the bill between all guests

Day 2 - Tip Calculator Simple program to calculate the tip amount and split the

Andre Schickhoff 1 Jan 24, 2022
Telegram bot to download almost all from Instagram

Instagram Manager Bot The most advanced Instagram Downloader Bot. Please fork this repository don't import code Made with Python3 (C) @subinps Copyrig

SUBIN 300 Dec 30, 2022
The Easy-to-use Dialogue Response Selection Toolkit for Researchers

Easy-to-use toolkit for retrieval-based Chatbot Our released data can be found at this link. Make sure the following steps are adopted to use our code

GMFTBY 32 Nov 13, 2022
A module to complement discord.py that has Music, Paginator and Levelling.

discord-super-utils A modern python module including many useful features that make discord bot programming extremely easy. Features Modern leveling m

Yash 106 Dec 19, 2022
One of Best renamer bot with python

🌀 One of Best renamer bot repo Please Give a ☆ if You like This Open Source and Don't Forget to Follow Me On Github For More Repos And Codes. Scrappe

1 Dec 14, 2021
This Lambda will Pull propagated routes from TGW and update VPC route table

AWS-Transitgateway-Route-Propagation This Lambda will Pull propagated routes from TGW and update VPC route table. Tested on python 3.8 Lambda AWS INST

4 Jan 20, 2022