Talking with my Nextcloud instance - API basics

Hi,

I’d like to create a small app that stores data in my own cloud. Basically a small board that reads temperature and then stores it (e.g. in a table). So I’m looking for some API basics - not to develop inside NextCloud, but to talk with my instance.

So basically:

  • Step 1: inside my NextCloud instance, where can I set up a way to authenticate my API? (oAuth2? username and password? …)
  • Step 2: where can I find documentation on the available endpoints?

I read somewhere that apps also have a way to expose endpoints. Is there an url on my site that can show me what API endpoints I have at my availability?

Hello!

If you do a bit of searching online, you’ll quickly come across a few results:
You will probably want to verify yourself with a username and password for API access. Your normal username and password would work here. If you have set up 2-factor authentication, you need to make sure that you create a so-called app password that you then use for authentication (under Settings → Security → scroll down → enter app name and create new password).

The API documentation is available here:
https://docs.nextcloud.com/server/latest/developer_manual/_static/openapi.html#/
I hope I was able to help you!
Best regards,
schBenedikt

Yes, I also found that page… but couldn’t make anything from it.
No explanation on how to use the endpoints
No explanation of what an endpoint does/means
No code samples
No documentation on how/where to set up that oAuth flow or how to get the bearer code.

So I believe this is possibly a useful reference once you’ve got the basics… I am sorely missing some more guides or explanation. But maybe that’s because I’m not a professional developer.

As a test, you should write a programme that uploads a file to Nextcloud, for example. Which programming language do you want to programme in?

I’d be writing in Python, and maybe later on also in curl. Both are fine for me.

Perhaps you can first programme a basic “framework” in Python which you can then expand. I asked a KI. Here are two examples. One with username/password an one with app password. Maybe you can test them first.

version with username/password

import requests

def upload_file_nextcloud(username, password, nextcloud_url, file_path, remote_path):
    # URL for the upload
    upload_url = f"{nextcloud_url}/remote.php/dav/files/{username}/{remote_path}"

    # Open the file and upload it
    with open(file_path, 'rb') as file:
        response = requests.put(upload_url, data=file, auth=(username, password))

    if response.status_code == 201:
        print("File uploaded successfully!")
    else:
        print(f"Error uploading file: {response.status_code} - {response.text}")

# Example call
username = 'your_username'
password = 'your_password'
nextcloud_url = 'https://your-nextcloud-url.com'
file_path = 'local/path/to/file.txt'
remote_path = 'remote/path/to/file.txt'

upload_file_nextcloud(username, password, nextcloud_url, file_path, remote_path)

version with app password

import requests

def upload_file_nextcloud_app_password(username, app_password, nextcloud_url, file_path, remote_path):
    # URL for the upload
    upload_url = f"{nextcloud_url}/remote.php/dav/files/{username}/{remote_path}"

    # Open the file and upload it
    with open(file_path, 'rb') as file:
        response = requests.put(upload_url, data=file, auth=(username, app_password))

    if response.status_code == 201:
        print("File uploaded successfully!")
    else:
        print(f"Error uploading file: {response.status_code} - {response.text}")

# Example call
username = 'your_username'
app_password = 'your_app_password'
nextcloud_url = 'https://your-nextcloud-url.com'
file_path = 'local/path/to/file.txt'
remote_path = 'remote/path/to/file.txt'

upload_file_nextcloud_app_password(username, app_password, nextcloud_url, file_path, remote_path)
2 Likes

Thanks, that’s indeed a good starting point. It’s pretty straightforward.
I also figured out the oAuth flow too (and where to set up an API-key… it’s a bit hidden but documentation is on its way)

So next I wanted to see if I could talk to the Forms API, as I found this in the github repo:

Now I’m confused… in the beginning I read:
Base URL for all calls to the forms API is <nextcloud_base_url>/ocs/v2.php/apps/forms

… and then a bit further down: (picked the first one: List Owned Endpoints)
Endpoint: /api/v2.4/forms

I can’t figure out what the correct URL-path for this endpoint is.

This is my current code (settings.py is a companion file containing credentials and ULR):

import requests
import settings


class NextcloudFormHandler:
    def __init__(self, nextcloud_url: str, username: str, password: str):
        self.nextcloud_url = nextcloud_url
        self.auth = (username, password)
        self.headers = {
            'OCS-APIRequest': 'true',
            'Content-Type': 'application/json',
        }
    def get_forms(self) -> None:
        try:
            response = requests.get(
                f'{self.nextcloud_url}/ocs/v2.php/forms',
                headers=self.headers,
                auth=self.auth
            )

            if response.status_code == 200:
                print('Forms retrieved successfully')
                print('Response:', response.json())
            else:
                print(f'Failed to retrieve forms: {response.status_code} - {response.text}')
        except requests.exceptions.RequestException as e:
            print(f'An error occurred: {e}')

def main():

    form_creator = NextcloudFormHandler(settings.NEXTCLOUD_URL, settings.USERNAME, settings.PASSWORD)
    form_creator.get_forms()  # Retrieve all forms

if __name__ == '__main__':
    main()

But this is giving a 404, that the endpoint is not found.
I tried these endpoints:

… for other people looking into this… there is an app in the NC App store to see what endpoints are available to you (incl. a nice call-tester).