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 melhor maneira de atender seus clientes no Telegram!

Clientes.Chat Sobre o serviço Configuração Banco de Dados Variáveis de Ambiente Docker Python Heroku Contribuição Sobre o serviço A maneira mais organ

Gabriel R F 10 Oct 12, 2022
A Discord Server Cloner Which Can Clone Any Discord Server In Just Few Minutes

A Discord Server Cloner Which Can Clone Any Discord Server In Just Few Minutes.

samet 4 Jul 23, 2022
UniHub API is my solution to bringing students and their universities closer

🎓 UniHub API UniHub API is my solution to bringing students and their universities closer... By joining UniHub, students will be able to join their r

Abdelbaki Boukerche 5 Nov 21, 2021
A course on getting started with the Twitter API v2 for academic research

Getting started with the Twitter API v2 for academic research Welcome to this '101 course' on getting started with academic research using the Twitter

@TwitterDev 426 Jan 04, 2023
Dicha herramienta esta creada con una api... esta api permite enviar un SMS cada 12 horas dependiendo del pais... Hay algunos paises y operadoras no están soportados.

SMSFree pkg install python3 pip install requests git clone https://github.com/Hidden-parker/SMSFree cd SMSFree python sms.py DISFRUTA... Dicha herrami

piter 2 Nov 14, 2021
Python interface to the World Bank Indicators and Climate APIs

wbpy A Python interface to the World Bank Indicators and Climate APIs. Readthedocs Github source World Bank API docs The Indicators API lets you acces

Matt Duck 47 Oct 31, 2022
The EscapePod Python SDK for Cyb3rVector's EscapePod Extension Proxy

EscapePod Extension SDK for Python by cyb3rdog This is the EscapePod Python SDK for Cyb3rVector's EscapePod Extension Proxy. With this SDK, you can: m

cyb3rdog 3 Mar 07, 2022
Deploy your apps on any Cloud provider in just a few seconds

The simplest way to deploy your apps in the Cloud Deploy your apps on any Cloud providers in just a few seconds ⚡ Qovery Engine is an open-source abst

Qovery 1.9k Dec 26, 2022
自动每天给女友发邮件

github acitons 发邮件 python 脚本 每天 7点半左右给女朋友发送邮件 天气来自: http://www.tianqiapi.com/ 文字图片来源:http://wufazhuce.com/ 风景图:https://qqlykm.cn/api/fengjing 土味情话:htt

gogobody 7 May 12, 2022
This is a cryptocurrency trading bot that analyses Reddit sentiment and places trades on Binance based on reddit post and comment sentiment. If you like this project please consider donating via brave. Thanks.

This is a cryptocurrency trading bot that analyses Reddit sentiment and places trades on Binance based on reddit post and comment sentiment. The bot f

Andrei 157 Dec 15, 2022
Hellomotoot - PSTN Mastodon Client using Mastodon.py and the Twilio API

Hello MoToot PSTN Mastodon Client using Mastodon.py and the Twilio API. Allows f

Lorenz Diener 9 Nov 22, 2022
A simple terminal UI for viewing fund P/L analysis through TEFAS

Tefas UI A simple terminal UI for viewing fund P/L analysis through TEFAS. Features (that my own bank's UI lack): Daily and weekly P/L FX comparisons

Batuhan Taskaya 4 Mar 14, 2022
Utility for downloading fanfiction in bulk from the Archive of Our Own

What is this? This is a program intended to help you download fanfiction from the Archive of Our Own in bulk. This program is primarily intended to wo

73 Dec 30, 2022
GitHub Usage Report

github-analytics from github_analytics import analyze pr_analysis = analyze.PRAnalyzer( "organization/repo", "organization", "team-name",

Shrivu Shankar 1 Oct 26, 2021
Simple integrate of API musixmatch.com with python

Python Musixmatch Simple integrate of API musixmatch.com with python Quick start $ pip install pymusixmatch or $ python setup.py install Authenticatio

Hudson Brendon 79 Dec 20, 2022
Wrapper for vk_api lib for faster bot buliding

Welcome to VKBotPod repository! Wrapper for vk_api lib for faster bot buliding Features Simple syntax Rich functionality Special thanks to movpushmov

NullPointerException 3 Jan 14, 2022
SimpleDCABot is a simple bot that buys crypto with a dollar-cost averaging strategy.

Simple Open Dollar Cost Averaging (DCA) Bot SimpleDCABot is a simple bot that buys crypto on a selected exchange at regular intervals for a prescribed

4 Mar 28, 2022
This code is for a bot which will find a Twitter user's most tweeted word and tweet that word, tagging said user

max_tweeted_word This code is for a bot which will find a Twitter user's most tweeted word and tweet that word, tagging said user The program uses twe

Yasho Bapat 1 Nov 29, 2021
A Simple and User-Friendly Google Collab Notebook with UI to transfer your data from Mega to Google Drive.

Mega to Google Drive (UI Added! 😊 ) A Simple and User-Friendly Google Collab Notebook with UI to transfer your data from Mega to Google Drive. ⚙️ How

Dr.Caduceus 18 Aug 16, 2022
Python wrapper for Revolt API

defectio is a direct implementation of the entire Revolt API and provides a way to authenticate and start communicating with Revolt servers. Similar interface to discord.py

Leon Bowie 26 Sep 18, 2022