title: Mock external API POST call in view from test view Python
body: <p>I have an external API POST call that is being made from within my <code>views.py</code> as such:</p>
  <pre><code>class MyView(APIView):
    def post(self, request):
      my_headers = {
        &quot;Content-Type&quot;: &quot;application/json&quot;
      }
      response = requests.post(&quot;https://some-external-api.com&quot;, data=json.dumps(request.data), headers=my_headers)
  
      return Response(status.response.status_code)
  </code></pre>
  <p>As you can see, it is a very simple case of making a POST call to the external API with the same data that is received to the views endpoint.</p>
  <p>Right now, I am trying to create a unit test for this, while mocking the response from &quot;https://some-external-api.com&quot; so I obviously don't have to make an actual call to it every time this unit test runs. But I am having difficulty as I can't get the mock aspect to work, and everytime the request is sent to the actual external endpoint.</p>
  <p>I know there are a lot of examples online, but nothing that I've tried seems to work. I've not seen examples whereby the mocked response should come from the view file itself. As of now, I have this:</p>
  <pre><code>@patch('requests.post')
  def test_external_api_call(self, mock_post)
    mock_post.return_value.ok = True
    response = self.client.post(reverse('my-view'), {
      //my random dummy json object goes here
    }, format='json')
  
    self.assertEqual(response.status_code, 200)
  </code></pre>
  <p>As I mentioned, with the above code, there is an actual call being made to &quot;https://some-external-api.com&quot; rather than it being mocked.</p>