Actually, there is a very simple answer to your question.
For representing a non-periodic function on the interval $[-L,L]$, we use
\begin{equation*}
f(x)=k_1+\frac{k_2x}{L}+\sum_{n=1}^{\infty} \left(A_n\cos\frac{n\pi x}{L}+B_n\sin\frac{n\pi x}{L}\right).
\end{equation*}
By evaluating the above series at $x=-L,L$, we get
\begin{equation*}
k_2=\frac{f(L)-f(-L)}{2}.
\end{equation*}
Let
\begin{equation*}
\tilde{f}(x)=f(x)-\frac{k_2x}{L}.
\end{equation*}
Then using the orthogonality of the sine and cosine functions, we get
\begin{align*}
k_1&=\frac{1}{2L}\int_{-L}^L \tilde{f}(\hat{x})\,d\hat{x}, \\
A_n&=\frac{1}{L}\int_{-L}^L \tilde{f}(\hat{x})\cos\frac{n\pi\hat{x}}{L}\,d\hat{x}, \\
B_n&=\frac{1}{L}\int_{-L}^L \tilde{f}(\hat{x})\sin\frac{n\pi\hat{x}}{L}\,d\hat{x}.
\end{align*}
For your function with $L=\pi$, we get
\begin{equation*}
x^3-\pi^2x=12\sum_{n=1}^{\infty} \frac{(-1)^n\sin(nx)}{n^3},
\end{equation*}
from which you get your desired summation.
For why the $x$ term should be present while representing non-periodic functions, see
https://www.awesomemath.org/wp-pdf-files/math-reflections/mr-2022-03/mr_3_2022_fourier.pdf
Besides eliminating the Gibbs phenomenon, you will get a much faster rate of convergence with the $x$ term present compared to when it is absent.