Next.js: Python api-route 404

Created on 1 Mar 2020  ·  6Comments  ·  Source: vercel/next.js

Bug report

Python api-route sends 404

Following the docs found here and here I tried creating an endpoint.py file within the /pages/api folder within my nextjs project.

Unfortunately it seems it only picks up *.js but not other extensions (I tried python and Golang).

To Reproduce

  1. Generate next project with create-next-app
  2. Create pages/api/endpoint.py and pages/api/requirements.txt with code from the documentation (a simple handler).
  3. Start server with now dev or next dev.
  4. Go to localhost:3000/api/endpoint
  5. Be greeted by a 404

Expected behavior

The endpoint should be handled by the serverless function in python and return whatever code is in the handler.

System information

  • OS: macOS 10.4 (mojave)
  • Version of Next.js: 9.2.2

Most helpful comment

It seems that you are confusing Next.js features (pages/api) with the top level api directory from ZEIT.

Next.js only supports JavaScript and TypeScript, the documentation can be found here: https://nextjs.org/docs/api-routes/introduction

The runtimes feature outlined here: https://zeit.co/docs/runtimes#official-runtimes/python is unrelated to Next.js.

All 6 comments

It seems that you are confusing Next.js features (pages/api) with the top level api directory from ZEIT.

Next.js only supports JavaScript and TypeScript, the documentation can be found here: https://nextjs.org/docs/api-routes/introduction

The runtimes feature outlined here: https://zeit.co/docs/runtimes#official-runtimes/python is unrelated to Next.js.

Thanks @timneutkens that worked.
Is there an easy way to run both /api/*.py and /page/api/*.js endpoints locally?
next makes /pages/api available while now dev makes /api functions available… but not both.

I was confused about /api vs /pages/api as well. According to @timneutkens comment it seems like it should work, assuming routes don't conflict.

So I just tried creating a clean next.js app using npm init next-app. I added a top-level /api folder containing the example cowsay python script from the Vercel serverless docs, including a top-level requirements.txt. When I deployed using the now CLI now, I get a warning message:

❗️  It is not possible to use `api` and `pages/api` at the same time, please only use one option

I checked the Now deployment and to my surprise it looks like everything works. I see my barebones Next.js home page, I can navigate to /api/cows to see the cowsay python output, and I can navigate to /api/hello to see the example JS api that ships with init next-app.

So if it works, why do we get warning messages that it doesn't work? Did I just get lucky? If it's just about route conflicts that would be pretty straightforward to document. I'm guessing there's more to the story.

I'm going to add my story to this, as it is the same issue and I can provide my setup for some more debugging context.


My React/NextJS front end has a Button component that fetches data via a serverless function when the button is clicked. I want to test this functionality during local development with the Vercel dev/CLI tools. I am getting a 404 result when attempting to access my lambda functions. Here are the approximate steps that I've gone through so far:

1) Create package.json with a dev script:

...
"scripts": {
    "dev": "yarn codegen && next --hostname=0.0.0.0 --port=3001",
}
...

2) Link to deployed vercel project
3) Create vercel.json to specify builds and routes:

...json
    "builds": [
        { "src": "*.html", "use": "@now/static" },
        { "src": "pages/api/*.py", "use": "@now/python" },
    ],
    "routes": [
        { "src": "/api/validate", "dest": "/pages/api/validate.py" }
    ]
...

4) Create my test Lambda function (in python):

from http.server import BaseHTTPRequestHandler
from datetime import datetime

class handler(BaseHTTPRequestHandler):

  def do_GET(self):
    self.send_response(200)
    self.send_header('Content-type', 'text/plain')
    self.end_headers()
    self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode())
    return

5) Create my Button component:

...
    <Button
        variant="contained"
        color="secondary"
        onClick={() => {
            fetch('api/validate')
                .then(response => { console.log(response)
                    response.json() })
                .then(data => console.log(data))
        }}
    >
        Generate sample dataset
    </Button>
...

6) Run vercel dev
7) Access website at localhost:3001 (next dev server address)
8) Click button

Result:

I'm receiving a 404 response

Note: I can access the lambda function from localhost:3000/pages/api/validate.py (vercel dev server address). This appears to manually kickstart the lambda function build and serve process. I thought that it should have been built and served already from the vercel.json specification and be available at localhost:3001/api/validate. This seems to agree with the Vercel documentation.

Note 2: Next dev/CLI tools build and serve javascript/typescript files just fine. I'm using python and Go functions as well, which are supported by Vercel dev/CLI but not Next

It seems that you are confusing Next.js features (pages/api) with the top level api directory from ZEIT.

Next.js only supports JavaScript and TypeScript, the documentation can be found here: https://nextjs.org/docs/api-routes/introduction

The runtimes feature outlined here: https://zeit.co/docs/runtimes#official-runtimes/python is unrelated to Next.js.

It looks like something has been update. But I'm still noob and I can't understand what has changed.
The Zeit link you provided redirects to a Next.js documentation about Python Serverless Functions

@GoulartNogueira I eventually figured out how to place my functions to get the desired result. This was a while ago, but I remember that the biggest issue was that correct docs were not easy to find. I believe I found the answer in a Github issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

havefive picture havefive  ·  3Comments

wagerfield picture wagerfield  ·  3Comments

flybayer picture flybayer  ·  3Comments

knipferrc picture knipferrc  ·  3Comments

renatorib picture renatorib  ·  3Comments