New in 2.4: Test runs you can trust See what's new →

Build a movie search app in React with a free movie API, no key needed

Share

Most movie app tutorials start with the same step: sign up for TMDB or OMDb and paste an API key into a .envfile. That's the right choice for a real product, because those services hold real catalogues. For a practice project, a portfolio demo or a UI test, the key is just in the way. It has to be kept out of git, it ends up in the browser bundle anyway, and a test run can run into the rate limit.

This post builds a small movie search app on the movies API on testingapis.com, which needs no key and no sign-up. You get search, sorting, pagination, a genre filter and loading and error states, in about 100 lines of JavaScript and React. Every request and response below came from the live API on 19 November 2026.

What the data looks like

The API holds 25 well-known films, from The Godfather to Oppenheimer, with directors, genres, cast, ratings, runtime and box office. One movie:

Terminal
$ curl -s https://api.testingapis.com/api/Movies/10
{"id":10,"title":"Spirited Away","director":"Hayao Miyazaki","year":2001,
 "genres":["Animation","Adventure","Fantasy"],"runtimeMinutes":125,"rating":8.6,
 "cast":["Rumi Hiiragi","Miyu Irino"],"boxOffice":395800000,
 "poster":"https://picsum.photos/seed/movie10/300/450"}
EndpointWhat it returns
GET /api/MoviesThe list, with search, filters, sorting and pagination
GET /api/Movies/{id}One movie, or 404
GET /api/Movies/genresThe 16 genres in use, sorted
GET /api/Movies/top?limit=5The highest-rated movies
GET /api/Movies/year/1994Movies released in that year
POSTPUT, PATCH and DELETE on the same paths, plus bulk create and delete

Search, sort and paginate

The list endpoint takes these query parameters, all optional:

ParameterExampleEffect
qq=darkCase-insensitive search in the title
sortsort=boxOfficeSort by any field
orderorder=descasc (the default) or desc
limitlimit=8Page size, 1 to 100. Without it you get every movie.
pagepage=21-based page number, used together with limit
any fielddirector=christopher nolanExact match, case-insensitive. This one returns four films.

The totals come back in headers, not in the body, so the body stays a plain array. CORS is open, and the headers are exposed, so a browser can read them:

Terminal
$ curl -s -D - -o /dev/null \
    "https://api.testingapis.com/api/Movies?q=the&sort=rating&order=desc&limit=3&page=1"
HTTP/1.1 200 OK
access-control-allow-origin: *
x-total-count: 7
x-page: 1
x-per-page: 3
x-total-pages: 3

The lesson on query parameters explains how to test parameters like these in general.

A small API module

Put the requests in one file, so the components never build URLs themselves. This works in the browser and in Node 18 or later, since both have fetch:

movies-api.js
const BASE = "https://api.testingapis.com/api/Movies";

export async function searchMovies({ q = "", sort = "rating", order = "desc", page = 1, limit = 8 } = {}) {
  const params = new URLSearchParams({ sort, order, page, limit });
  if (q) params.set("q", q);
  const res = await fetch(`${BASE}?${params}`);
  if (!res.ok) throw new Error(`Search failed with ${res.status}`);
  return {
    movies: await res.json(),
    // The header is 0 when nothing matches. Keep "page 1 of 1" in the UI.
    totalPages: Math.max(1, Number(res.headers.get("X-Total-Pages") ?? 1)),
  };
}

export async function getMovie(id) {
  const res = await fetch(`${BASE}/${id}`);
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Loading movie ${id} failed with ${res.status}`);
  return res.json();
}

export async function getGenres() {
  const res = await fetch(`${BASE}/genres`);
  if (!res.ok) throw new Error(`Loading genres failed with ${res.status}`);
  return res.json();
}

// genres is an array, and the list endpoint only filters on exact field values,
// so ?genres=Horror returns []. Filter in the client instead.
export async function moviesInGenre(genre) {
  const res = await fetch(BASE);
  if (!res.ok) throw new Error(`Loading movies failed with ${res.status}`);
  const all = await res.json();
  return all.filter((m) => m.genres.includes(genre));
}

Two details in there come from the API's behaviour. When a search matches nothing, X-Total-Pages is 0, which would render as "page 1 of 0". And because genresis an array, the exact-match filter can't select by genre. With 25 movies, fetching them all and filtering in the client costs one small request. The GraphQL endpoint can also do it on the server, with movies(genre: "Horror") { id title year }.

The search component

This works in a new Vite app (npm create vite@latest movies -- --template react). Replace App.jsx with it, or render it from there:

MovieSearch.jsx
import { useEffect, useState } from "react";
import { searchMovies } from "./movies-api.js";

export default function MovieSearch() {
  const [query, setQuery] = useState("");
  const [page, setPage] = useState(1);
  const [result, setResult] = useState({ movies: [], totalPages: 1 });
  const [status, setStatus] = useState("loading");

  useEffect(() => {
    // Wait until typing pauses, so each keystroke doesn't send a request.
    const timer = setTimeout(() => {
      setStatus("loading");
      searchMovies({ q: query, page })
        .then((data) => {
          setResult(data);
          setStatus("done");
        })
        .catch(() => setStatus("error"));
    }, 300);
    return () => clearTimeout(timer);
  }, [query, page]);

  return (
    <main>
      <input
        type="search"
        placeholder="Search titles"
        value={query}
        onChange={(e) => {
          setQuery(e.target.value);
          setPage(1);
        }}
      />

      {status === "loading" && <p>Loading…</p>}
      {status === "error" && <p>Couldn't load movies. Try again.</p>}
      {status === "done" && result.movies.length === 0 && <p>No movies match "{query}".</p>}

      <ul>
        {result.movies.map((m) => (
          <li key={m.id}>
            <img src={m.poster} alt={`Poster for ${m.title}`} width="100" height="150" />
            <strong>{m.title}</strong> ({m.year}), {m.director}, rated {m.rating}
          </li>
        ))}
      </ul>

      <button disabled={page <= 1} onClick={() => setPage(page - 1)}>Previous</button>
      <span> Page {page} of {result.totalPages} </span>
      <button disabled={page >= result.totalPages} onClick={() => setPage(page + 1)}>Next</button>
    </main>
  );
}

Typing resets the page to 1. Without that, a search for "the" that starts from page 3 would show nothing. The 300 ms timer keeps the request count down while someone types. If you use TypeScript, paste a response into JSON to TypeScript and you get a Movie interface.

Test the loading, error and empty states

A real API is fast and healthy most of the time, so these states rarely show up while you develop. Two query parameters force them on any request:

Terminal
# A slow network: the response arrives after 2 seconds.
$ curl -s -o /dev/null -w "%{http_code} %{time_total}s\n" "https://api.testingapis.com/api/Movies/1?delay=2"
200 2.135520s

# A server error, on demand.
$ curl -s "https://api.testingapis.com/api/Movies/1?error=503"
{"status":503,"error":"Service Unavailable","message":"Simulated error. Use ?error={code} to test different status codes.","simulated":true}

# A movie that doesn't exist.
$ curl -s https://api.testingapis.com/api/Movies/999
{"status":404,"error":"Not Found","message":"Movie with ID 999 does not exist."}

To see your spinner, add delay: 2 to the params in searchMovies for a moment. For the error message, add error: 503. Search for "zzz" to check the empty state. Remove both before you ship. The guide to mock error responses lists every status code you can request this way.

Add, edit and delete movies

The API also accepts writes, so you can build a "my watchlist" form or test a CRUD flow. This Python script creates a movie, changes its rating, deletes it and checks that it's gone:

movies.py
import requests

BASE = "https://api.testingapis.com/api/Movies"

new_movie = {
    "title": "Dune: Part Two",
    "director": "Denis Villeneuve",
    "year": 2024,
    "genres": ["Action", "Adventure", "Sci-Fi"],
    "runtimeMinutes": 166,
    "rating": 8.5,
    "cast": ["Timothée Chalamet", "Zendaya"],
}

created = requests.post(BASE, json=new_movie, timeout=10)
created.raise_for_status()
movie_id = created.json()["data"]["id"]
print("created", movie_id, created.status_code)

patched = requests.patch(f"{BASE}/{movie_id}", json={"rating": 8.6}, timeout=10)
print("patched", patched.json()["changed"])

deleted = requests.delete(f"{BASE}/{movie_id}", timeout=10)
print("deleted", deleted.status_code)

gone = requests.get(f"{BASE}/{movie_id}", timeout=10)
print("after delete", gone.status_code, gone.json()["message"])
Text
$ python movies.py
created 41 201
patched ['rating']
deleted 200
after delete 404 Movie with ID 41 does not exist.

Only title and director are required. The validation messages say which field is missing:

Terminal
# No title.
$ curl -s -X POST https://api.testingapis.com/api/Movies -H 'Content-Type: application/json' -d '{}'
{"status":400,"error":"Bad Request","message":"Missing required field: title"}

# PUT replaces the whole movie, so a partial body is rejected.
$ curl -s -X PUT https://api.testingapis.com/api/Movies/1 -H 'Content-Type: application/json' -d '{"title":"New title"}'
{"status":400,"error":"Bad Request","message":"Missing required field: director"}

# PATCH skips fields the movie doesn't have, and tells you.
$ curl -s -X PATCH https://api.testingapis.com/api/Movies/1 -H 'Content-Type: application/json' -d '{"studio":"WB"}'
{"message":"Movie patched successfully","changed":[],"ignored":["studio"],"data":{...}}

The CRUD testing lesson turns a script like this into assertions: status codes, the created body, and the 404 after the delete.

Common problems

SymptomCauseFix
?genres=HorrorReturns [], because genres is an arrayFetch all and filter, as in moviesInGenre
?q=nolanReturns [], because q searches titlesUse ?director=christopher nolan
The pager says page 1 of 0The search matched nothing, so X-Total-Pages is 0Math.max(1, …) on the header
Headers are null in the browserReading them before awaiting the response, or misspelling themRead res.headers.get("X-Total-Pages") after await fetch. The names aren't case-sensitive.
PUT returns 400PUT replaces the whole movieSend every field, or use PATCH for one
POST returns 415The body went out without Content-Type: application/jsonSet the header, or use json= in requests
Totals change between runsSomeone else added or deleted a movieRead the count instead of hard-coding it

Questions

Is it free, and do I need an account?

Yes, and no. The endpoints need no key, account or header. They are meant for learning, prototypes and tests, not as the backend of a public product.

When should I use TMDB or OMDb instead?

When you need real data: thousands of titles, real posters, release news, TV series. The API here has 25 films, so it suits a UI, a tutorial or a test suite, where a small, stable data set is easier to check.

Can I call it from a browser app on localhost?

Yes. Responses carry Access-Control-Allow-Origin: * and expose the pagination headers, so a Vite, Next.js or plain HTML page can call it directly, without a proxy.

Is there a GraphQL version?

Yes. POST /graphql has a movies query with an optional genre argument and a movie(id) query. The guide to the free GraphQL API shows how to call it.

How does it compare with other free fake APIs?

See the comparison of free fake APIs, which tested what each one does with a write.

The movies API reference has every endpoint, with a form to run each request in the browser. Bulk create and delete are there too, if you need to load a test data set in one call.