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
An App to get Ko-Fi payment updates on Telegram.

Deployments. Heroku.com 🚀 Replit.com 🌀 Make sure your app runs 24*7 Zeet.co 💪 Use this :~ Get Bot token from @botfather 🤖 Get ID where you want to

Jainam Oswal 16 Nov 12, 2022
Ethone-Selfbot - Open Source Discord Self-Bot, written in discord.py

Ethone SB Table of contents Newest open-source Discord SelfBot with useful commands and easy documentation on how to add your own and change the exist

Ethone 3 Jan 08, 2022
This Wrapper is a Discum Copy With Addons, original one is made by Merubokkusu

Remaded Discum Its not Official Discum Wrapper ! This Wrapper is a Discum Copy With Addons, original one is made by Merubokkusu Authors @merubokkusu (

discum-remaded 8 Aug 09, 2022
Prabashwara's Pm Bot repository. You can deploy and edit this repository.

Tᴇʟᴇɢʀᴀᴍ Pᴍ Bᴏᴛ | Prabashwara's PM Bot Unmaintained. The new repo of @Pm-Bot is private. (It is no longer based on this source code. The completely re

Rivibibu Prabshwara Ⓒ 2 Jul 05, 2022
Auto like & auto followers facebook

Auto like & auto followers facebook

Fahmi Dev 23 Dec 08, 2022
Discord bot that displays the current Swatch Internet Time (.beat) as a status.

Internet-Time-Display Discord bot that displays the current Swatch Internet Time (.beat) as a status. Visit the website! Add the bot to your server! A

2 Mar 15, 2022
Project for the discipline of Visual Data Analysis at EMAp FGV.

Analysis of the dissemination of fake news about COVID-19 on Twitter This project was the final work for the discipline of Visual Data Analysis of the

Giovani Valdrighi 2 Jan 17, 2022
API RestFull de uma clinica, onde vai efetuar os agendamentos dos pacientes e mostrar o historicos de cada agendamentos

API REstFull O que tem na API Usado para clinicas. Cadastro de pacientes. Agendamentos de pacientes. Históricos dos agendamentos vinculados com a tabe

Lucas Silva 3 Aug 29, 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
🦈 Blahaj is a discord bot that shares random images of himself on discord.

🦈 Blahaj Bot Blahaj is a discord bot that shares random images of himself on discord. ⚙️ Developer's Guide To use the bot, follow along the steps Hea

Atul Anand 3 Oct 21, 2022
Python On WhatsApp - Run your python codes on whatsapp along with talking to a chatbot

Python On WhatsApp Run your python codes on whatsapp along with talking to a chatbot This is a small python project to run python on whatsapp. and i c

Prajjwal Pathak 32 Dec 30, 2022
AWS EC2 S3 Automated With python

AWS_EC2_S3_Automated Description This programme is a Python3 script that utilizes Boto3 to automate the process of creating an AWS EC2 instance with a

niall_crowe 2 Nov 16, 2021
A bot framework for Reddit to manage threads, wiki pages, widgets, menus and more.

Sub Manager Sub Manager is a bot framework for Reddit to automate a variety of tasks on one or more subreddits, and can be configured and run without

r/SpaceX 3 Aug 26, 2022
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
RP2 is a privacy-focused, free, open-source US cryptocurrency tax calculator

Privacy-focused, free, open-source cryptocurrency US tax calculator, up to date for 2021: it handles multiple coins/exchanges and computes long/short-term capital gains, cost bases, in/out lot relati

eprbell 123 Jan 04, 2023
Reddit cli to slack at work

Reddit CLI (v1.0) Introduction Why Reddit CLI? Coworker who sees me looking at something in a browser: "Glad you're not busy; I need you to do this, t

3 Jun 22, 2021
自用直播源集合,附带检测与分类功能。

myiptv 自用直播源集合,附带检测与分类功能。 为啥搞 TLDR: 太闲了。 自己有收集直播源的爱好,和录制直播源的需求。 一些软件自带的直播源太过难用。 网上现有的直播源太杂,且缺乏检测。 一些大源缺乏持续更新,如 iptv-org。 使用指南与 TODO 每次进行大更新后都会进行一次 rel

abc1763613206 171 Dec 11, 2022
Posts word definitions on Twitter daily

Word Of The Day bot Post daily word definitions on social media. Twitter account: https://twitter.com/WordOfTheDay_B Introduction The goal of this pro

Lucas Rijllart 1 Jan 08, 2022
Telegram PHub Bot using ARQ Api and Pyrogram. This Bot can Download and Send PHub HQ videos in Telegram using ARQ API.

Tg_PHub_Bot Telegram PHub Bot using ARQ Api and Pyrogram. This Bot can Download and Send PHub HQ videos in Telegram using ARQ API. OS Support All linu

TheProgrammerCat 13 Oct 21, 2022
Powerful and Advance Telegram Bot with soo many features😋🔥❤

Chat-Bot Reach this bot on Telegram Chat Bot New Features 🔥 ✨ Improved Chat Experience ✨ Removed Some Unnecessary Commands ✨ Added Facility to downlo

Sanila Ranatunga 10 Oct 21, 2022