"POST /api/analyze/ HTTP/1.1" 404 3774 Not Found: /api/analyze/

Hey everybody, thank you for clicking on my post. Any sort of help is appreciated
I have an issue with the API when the POST request isn’t getting successful.
This is my views.py page,

from django.shortcuts import render  
from django.http import JsonResponse  
from django.apps import apps  
from ssr.forms import InputForm 
from django.views.decorators.csrf import csrf_exempt 
import json

def home(request):  
    return render(request, 'index.html', {'title': 'Home', 'message': 'Welcome to the homepage!'})  

def index(request):  
    return render(request, 'index.html')  

def analysis(request):  
    return render(request, 'analysis.html')  

def contact(request):  
    return render(request, 'contact.html')  

def documentation(request):  
    return render(request, 'documentation.html')  

def gallery(request):  
    return render(request, 'gallery.html')  

def result(request):  
    form = InputForm(request.POST or None)  

    if request.method == 'POST':  
        if form.is_valid():  
            ssr_type = form.cleaned_data['ssrtype']  
            chromosome = form.cleaned_data['chromosome']  
            start = form.cleaned_data['start']  
            end = form.cleaned_data['end']  

            try:  
                model_class = apps.get_model('ssr', ssr_type.lower() + 's')  
                objects = model_class.objects.filter(
                    Chromosome=chromosome,  
                    Start__gte=start,  
                    End__lte=end  
                ).values('ID', 'Chromosome', 'SSRtype', 'SSRsequence', 'Size', 'Start', 'End')  

                context = {  
                    'objects': list(objects),  
                    'form': form  
                }  
                return render(request, 'result.html', context)  
            except LookupError:  
                form.add_error(None, 'The specified SSR model does not exist!')  
            except Exception as e:  
                form.add_error(None, 'The specified SSR model does not exist!')  

    return render(request, 'result.html', {'form': form})

Welcome @TaraFielsys !

First a side note: When posting code here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of fixing your original post for you.)

Generally speaking, a 404 is going to occur when you’re issuing a request for a url that isn’t defined.

We’ll need to see your root urls.py file, along with the urls.py file handling the /api/ portion of your urls.config.

Thanks for the reply and also for correcting the code. Any help would be appreciated :slight_smile:
This is my project’s urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import include


urlpatterns = [
    path('admin/', admin.site.urls),
    path("",include("ssr.urls")),
    path('api/analyze', include('ssr.urls')),
]

This is my app’s urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('analysis.html', views.analysis, name='analysis'),
    path('index.html', views.index, name='home'),
    path('contact.html', views.contact, name='contact'),
    path('documentation.html', views.documentation, name='documentation'),
    path('gallery.html', views.gallery, name='gallery'),
    path('result.html',  views.result, name='result'),
    path('', views.home, name='home'),
    path('api/analyze/', analyze, name='analyze'), 
]

This is my app.js file

document.addEventListener('DOMContentLoaded', function() {
  const speciesSelect = document.getElementById('species');
  const chromosomeInput = document.getElementById('chromosome');
  const ssrtypeSelect = document.getElementById('ssrtype');
  const startInput = document.getElementById('Start');
  const endInput = document.getElementById('End');
  const submitButton = document.getElementById('submit-btn');
  const chartCanvas = document.getElementById('chart-canvas');
  
  // Disable submit button initially
  submitButton.disabled = true;

  // Function to enable/disable submit button based on form validation
  function validateForm() {
    const species = speciesSelect.value;
    const chromosome = chromosomeInput.value;
    const ssrtype = ssrtypeSelect.value;
    const start = startInput.value;
    const end = endInput.value;

    // Enable the submit button only if all fields are filled
    submitButton.disabled = !(species && chromosome && ssrtype && start && end);
  }

  // Event listeners for form inputs
  speciesSelect.addEventListener('change', validateForm);
  chromosomeInput.addEventListener('input', validateForm);
  ssrtypeSelect.addEventListener('change', validateForm);
  startInput.addEventListener('input', validateForm);
  endInput.addEventListener('input', validateForm);

  // Handle form submission
  submitButton.addEventListener('click', function(event) {
    event.preventDefault(); // Prevent default form submission

    // Get form data
    const species = speciesSelect.value;
    const chromosome = chromosomeInput.value;
    const ssrtype = ssrtypeSelect.value;
    const start = startInput.value;
    const end = endInput.value;

    // Create an object with form data
    const formData = {
      species: species,
      chromosome: chromosome,
      ssrtype: ssrtype,
      start: parseInt(start, 10), // Convert to integer
      end: parseInt(end, 10)        // Convert to integer
    };

    // Send form data to the PostgreSQL API using a POST request
    fetch('/api/analyze/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData)
    })
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok ' + response.statusText);
      }
      return response.json();
    })
    .then(data => {
      // Handle the response from the server
      console.log(data);

      // Update the chart with the analysis results if applicable
      if (data.chart_data) {
        updateChart(data.chart_data);
      } else {
        console.error('No chart data returned from the server');
      }
    })
    .catch(error => {
      // Handle any errors
      console.error('Error:', error);
    });
  });

  // Function to update the chart with analysis results
  function updateChart(chartData) {
    // Clear the canvas
    chartCanvas.innerHTML = '';
    new Chart(chartCanvas, {
      type: 'bar',
      data: {
        labels: chartData.labels, // Assuming chartData contains labels
        datasets: [{
          label: 'SSR Count',
          data: chartData.data, // Assuming chartData contains data
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          borderColor: 'rgba(75, 192, 192, 1)',
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
            precision: 0
          }
        }
      }
    });
  }
});

@KenWhitesell Thank you for showing interest, I figured out my mistake.

from django.urls import path
from . import views

urlpatterns = [
    path('analysis.html', views.analysis, name='analysis'),
    path('index.html', views.index, name='home'),
    path('contact.html', views.contact, name='contact'),
    path('documentation.html', views.documentation, name='documentation'),
    path('gallery.html', views.gallery, name='gallery'),
    path('result.html',  views.result, name='result'),
    path('', views.home, name='home'),
    path('api/analyze/', **views.analyze**, name='analyze'), 
]

Now I can see the POST requests but I cannot see the output (data retrieved from the database). Can you help me with that?