# Oauth2 REST API

**URL:** <https://forum.djangoproject.com/t/oauth2-rest-api/15485>\
**Category:** Forms & APIs\
**Created:** [August 18, 2022, 9:47pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485 "2022-08-18T21:47:34Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![MeghvShetty](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/meghvshetty/32/6212_2.png) [@MeghvShetty](https://forum.djangoproject.com/u/MeghvShetty)\
**Post date:** [August 18, 2022, 9:47pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/1 "2022-08-18T21:47:35Z")

</div>

Hello Guys,  
I want to automate my tweets from my Django application. I want to make a post(on Twitter) each time I write and publish a blog. I have used REST API with OAuth2 in a simple python program and run it via CLI. But This is the 1st time I will be integrating into an application. How do I get started so I can post my blog (image, heading) to Twitter using Django?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 18, 2022, 10:07pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/2 "2022-08-18T22:07:34Z")

</div>

The same way you would perform any functionality in Django.

The browser issues a request to a URL, Django dispatches that request to a view. The view receives a request and returns a response.  
Whatever happens between receiving the request and returing a response is _entirely_ up to you.

---

<div class="post-metadata">

**Author:** ![MeghvShetty](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/meghvshetty/32/6212_2.png) [@MeghvShetty](https://forum.djangoproject.com/u/MeghvShetty)\
**Post date:** [August 19, 2022, 7:18am UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/3 "2022-08-19T07:18:00Z")

</div>

Hi,  
So I write my logic in Views.py and when a blog post is made it runs the API function(send the current post head and image).

Could you please share resources if you have any? most of the posts & videos just show how to build a rest API within Django.

Do we have any package that can handle oauth2 authentication ? I see a couple but am know which to use any suggestions on that?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 19, 2022, 1:03pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/4 "2022-08-19T13:03:19Z")

</div>

> [@MeghvShetty](#):
>
> So I write my logic in Views.py and when a blog post is made it runs the API function(send the current post head and image).

Correct.

> [@MeghvShetty](#):
>
> Could you please share resources if you have any?

It seems like you have your own resource:

> [@MeghvShetty](#):
>
> I have used REST API with OAuth2 in a simple python program and run it via CLI.

You’re going to be using the same code - only you’re going to be using it within a view.

---

<div class="post-metadata">

**Author:** ![MeghvShetty](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/meghvshetty/32/6212_2.png) [@MeghvShetty](https://forum.djangoproject.com/u/MeghvShetty)\
**Post date:** [August 20, 2022, 6:04pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/5 "2022-08-20T18:04:46Z")

</div>

```auto
from requests_oauthlib import OAuth1Session
import json

payload = {
    "text":"New World!"
}

# Be sure to add replace the text of the with the text you wish to Tweet. You can also add parameters to post polls, quote Tweets, Tweet with reply settings, and Tweet to Super Followers in addition to other features.
payload = {"text": "Hello world! Post from API"}

# Get request token
#request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
#oauth = OAuth1Session(client_key= consumer_key, client_secret= consumer_secret)

oauth = OAuth1Session(
    consumer_key,
    client_secret=consumer_secret,
    resource_owner_key=access_token,
    resource_owner_secret=access_token_secret,
)

# Making the request
response = oauth.post(
    "https://api.twitter.com/2/tweets",
    json=payload,
)

if response.status_code != 201:
    raise Exception(
        "Request returned an error: {} {}".format(response.status_code, response.text)
    )

print("Response code: {}".format(response.status_code))

# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))

```

This is my standalone code for posting using CLI

In view.py

```nohighlight
    model = Post
    form_class = PostForms
    template_name = 'add_post.html'
    success_url = reverse_lazy('blogview')
    #fields = ' __all__'

```

in forms.py

```auto
class PostForms(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('poster','title', 'author', 'category','snippet', 'body')

        widgets = {
            'title' : forms.TextInput(attrs={'class':'form-control'}),
            'author' : forms.TextInput(attrs={'class':'form-control', 'value': '','id':'current_user','type':'hidden'}),
            #'author' : forms.Select(attrs={'class':'form-control'}),
            'category': forms.Select(attrs={'class':'form-control'}),
            'snippet' : forms.TextInput(attrs={'class':'form-control'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),
           
        

        }

```

How do I do it?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 20, 2022, 7:12pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/6 "2022-08-20T19:12:01Z")

</div>

You didn’t show your complete view, but from what I can see, it appears most likely that you’re using one of the Django-provided CBVs.

When you have _any_ of the Django CBVs, what method do you override to add custom functionality when a valid form is submitted?

Note - if you’re not all that familiar with how CBVs work, you may want to review the documentation starting at [Class-based views | Django documentation | Django](https://docs.djangoproject.com/en/4.1/topics/class-based-views/). You may also find the [Classy Class-Based Views](https://ccbv.co.uk/) site and the [CBV diagrams](https://www.brennantymrak.com/articles/django-class-based-views-diagrams.html) page to be helpful.

---

<div class="post-metadata">

**Author:** ![MeghvShetty](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/meghvshetty/32/6212_2.png) [@MeghvShetty](https://forum.djangoproject.com/u/MeghvShetty)\
**Post date:** [August 20, 2022, 7:53pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/7 "2022-08-20T19:53:21Z")

</div>

```auto
from gettext import Catalog
from unicodedata import category
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, TemplateView, CreateView, UpdateView, DeleteView
from cavertech.models import Post, Contact, Category
from cavertech.forms import PostForms,EditForms

# Create your views here.
#def home(request):
# return render(request, 'home1.html',{})

class Home_view(CreateView): # Hoeme page view 
    model = Contact
    template_name = 'home.html'
    fields =['email']
    success_url = reverse_lazy('home')

class Blog_view(ListView): # Blog list view  
    model = Post
    template_name = 'blog_list.html'
    cats = Category.objects.all()
    ordering = ['-date']

class Article_view(DetailView): # Blog detail view 
    model = Post
    template_name = 'article_view.html'

class Create_post_view(CreateView): # Create Blog
    model = Post
    form_class = PostForms
    template_name = 'add_post.html'
    success_url = reverse_lazy('blogview')
    #fields = ' __all__'

class Update_post_view(UpdateView): # update Blog
    model = Post
    form_class = EditForms
    template_name = 'update_post.html'
    success_url = reverse_lazy('blogview')
    #fields = ['title', 'author', 'body']

class Delete_post_view(DeleteView): 
    model = Post
    template_name = 'delete_post.html'
    success_url = reverse_lazy('blogview')

#class Category_view(ListView):
# model = Post
# template_name = 'categories_view.html'

def Category_view(request, cats): # fuction view 
    category_post = Post.objects.filter(category=cats)
    return render(request, 'categories_view.html', {'category_post': category_post})

```

this is my complete view.py  
I am not overriding any method.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 20, 2022, 11:20pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/8 "2022-08-20T23:20:16Z")

</div>

Ok, let me rephrase my question.

If you wanted to override a method to add functionality to a view that will execute when a valid form is submitted, what method would you override?

---

<div class="post-metadata">

**Author:** ![MeghvShetty](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/meghvshetty/32/6212_2.png) [@MeghvShetty](https://forum.djangoproject.com/u/MeghvShetty)\
**Post date:** [August 21, 2022, 10:44am UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/9 "2022-08-21T10:44:39Z")

</div>

I see the create post view would be the one. once the post is created I would like to do an API call to send the title and image of the blog to twitter

```auto
class Create_post_view(CreateView): # Create Blog
    model = Post
    form_class = PostForms
    template_name = 'add_post.html'
    success_url = reverse_lazy('blogview')
    #fields = ' __all__'

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 21, 2022, 10:56am UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/10 "2022-08-21T10:56:41Z")

</div>

> [@MeghvShetty](#):
>
> I see the create post view would be the one.

Ok, that’s the view that you want to change.

When you want to change the behavior of a CBV, you generally override one (or more) of the methods that are defined for that view.

Which method do you think you want to override to add your functionality to do this? (You’ll want to do this after the form has been submitted and validated.)

---

<div class="post-metadata">

**Author:** ![MeghvShetty](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/meghvshetty/32/6212_2.png) [@MeghvShetty](https://forum.djangoproject.com/u/MeghvShetty)\
**Post date:** [August 21, 2022, 4:35pm UTC](https://forum.djangoproject.com/t/oauth2-rest-api/15485/11 "2022-08-21T16:35:56Z")

</div>

> [@KenWhitesell](#):
>
> (You’ll want to do this after the form has been submitted and validated.)

Yes That is what I want to do
