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
Simple Python script that lets you upload image/video to imgur

Pymgur 🐍 Simple Python script that lets you upload image/video to imgur! Usage 🔨 Git Clone this repository install the requirements (pip install -r

3 Feb 20, 2022
This checks that your credit card is valid or not

Credit_card_Validator This checks that your credit card is valid or not. Where is the app ? main.exe is the application to run and main.py is the file

Ritik Ranjan 1 Dec 21, 2021
Fully asynchronous trace.moe API wrapper

AioMoe Fully asynchronous trace.moe API wrapper Installation You can install the stable version from PyPI: $ pip install aiomoe Or get it from github

2 Jun 26, 2022
⚡ A really fast and powerful Discord Token Checker

discord-token-checker ⚡ A really fast and powerful Discord Token Checker How To Use? Do pip install -r requirements.txt in your command prompt Make to

vida 25 Feb 26, 2022
Telegram Userbot to steram youtube live or Youtube vido in telegram vc by help of pytgcalls

TGVCVidioPlayerUB Telegram Userbot to steram youtube live or youtube vidio in telegram vc by help of pytgcalls Commands = Vidio Playing 🎧 stream :

Achu biju 3 Oct 28, 2022
Fix Twitter video embeds in Discord

TwitFix very basic flask server that fixes twitter embeds in discord by using youtube-dl to grab the direct link to the MP4 file and embeds the link t

Robin Universe 682 Dec 28, 2022
Python library for generating sequences with uniform stimulus history

Sampling Euler tours for uniform stimulus history Table of Contents About Examples Experiment 1 Experiment 2 Experiment 3 Experiment 4 Experiment 5 Co

5 Nov 11, 2021
Python API Client for Close

Close API A convenient Python wrapper for the Close API. API docs: http://developer.close.com Support: Close 56 Nov 30, 2022

Proxy-Bot - Python proxy bot for telegram

Proxy-Bot 🤖 Proxy bot between the main chat and a newcomer, allows all particip

Anton Shumakov 3 Apr 01, 2022
Exports saved posts and comments on Reddit to a csv file.

reddit-saved-to-csv Exports saved posts and comments on Reddit to a csv file. Columns: ID, Name, Subreddit, Type, URL, NoSFW ID: Starts from 1 and inc

70 Jan 02, 2023
Integrating the Daraja-Api with Python language

Mpesa-Daraja-Api Integrating the Daraja-Api with Python language. Credentials.py file This file contains the consumer key and the consumer secrete key

Morvin Ian 3 Nov 09, 2022
The Fastest multi spambot of Telegram 🤞 🤞

Revil Spam Bot The Fastest multi spambot of Telegram 🤞 🤞 𝚂𝚄𝙿𝙿𝙾𝚁𝚃 🖤 ᴄʀᴇᴀᴛᴏʀ 🖤 ⚡ 𝓡𝓮𝓿𝓲𝓵 𝓗𝓾𝓷𝓽𝓮𝓻 𝔐𝔲𝔩𝔱𝔦 ẞø✞︎ ⚡ 𝓐 𝕾мοοτн 𝓐и∂ 𝕱

REVIL HUNTER 4 Dec 08, 2021
✖️ Unofficial API of 1337x.to

✖️ Unofficial Python API Wrapper of 1337x This is the unofficial API of 1337x. It supports all proxies of 1337x and almost all functions of 1337x. You

Hemanta Pokharel 71 Dec 26, 2022
IMDb + Auto + Unlimited Filter BoT

Telegram Movie Bot Features Auto Filter Manuel Filter IMDB Admin Commands Broadcast Index IMDB search Inline Search Random pics ids and User info Stat

Jos Projects 82 Dec 27, 2022
Easily update resume to naukri with one click

NAUKRI RESUME AUTO UPDATER I am using poetry for dependencies. you can check or change in data.txt file for username and password Resume file must be

Rahul.p 1 May 02, 2022
Simulation artifacts, core components and configuration files to integrate AWS DeepRacer device with ROS Navigation stack.

AWS DeepRacer Overview The AWS DeepRacer Evo vehicle is a 1/18th scale Wi-Fi enabled 4-wheel ackermann steering platform that features two RGB cameras

AWS DeepRacer 31 Nov 21, 2022
A Chip-8 emulator written using Python's default libraries

Chippure A Chip-8 emulator written using Python's default libraries. Instructions: Simply launch the .py file and type the name of the Chip8 ROM you w

5 Sep 27, 2022
This wrapper now has async support, its basically the same except it uses asyncio

This is a python wrapper for my api api_url = "https://api.dhravya.me/" This wrapper now has async support, its basically the same except it uses asyn

Dhravya Shah 5 Mar 10, 2022
Pure Python 3 MTProto API Telegram client library, for bots too!

Telethon ⭐️ Thanks everyone who has starred the project, it means a lot! Telethon is an asyncio Python 3 MTProto library to interact with Telegram's A

LonamiWebs 7.3k Jan 01, 2023
An inline Telegram bot to keep your private messages hidden from prying eyes.

Hide This Bot Hide This Bot is an inline Telegram bot to keep your private messages hidden from prying eyes.     How do I host it? Here is a brief gui

41 Dec 02, 2022