Get Started

Set up Prisma

Goals

On this page, you will learn how to:

  • Install the Prisma CLI
  • Set up Prisma using Docker
  • Configure your Prisma API
  • Generate the Prisma client
  • Read and write data using the Prisma client

Prisma 1 is currently in maintenance mode. We recommend to get started with Prisma 2 instead.

Install the Prisma CLI

The Prisma CLI is used for various Prisma workflows. You can install it using Homebrew or NPM:

Homebrew
NPM
brew tap prisma/prisma
brew install prisma
Copy

Install Docker

To use Prisma locally, you need to have Docker installed on your machine. If you don't have Docker yet, you can download the Docker Community Edition for your operating system here.

Don't want to use Docker? Check out the new Prisma 2 which removes the need to host the Prisma server using Docker.

Set up and connect Prisma with a database

Create new directory

mkdir hello-world
cd hello-world
Copy

Create Docker Compose file

To launch Prisma on your machine, you need a Docker Compose file that configures Prisma and specifies the database it can connect to.

touch docker-compose.yml
Copy

Add Prisma and database Docker images

Paste the following contents into the Docker Compose file you just created:

MySQL
PostgreSQL
MongoDB
version: '3'
services:
  prisma:
    image: prismagraphql/prisma:1.34
    restart: always
    ports:
      - '4466:4466'
    environment:
      PRISMA_CONFIG: |
        port: 4466
        databases:
          default:
            connector: mysql
            host: mysql
            port: 3306
            user: root
            password: prisma
  mysql:
    image: mysql:5.7
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: prisma
    volumes:
      - mysql:/var/lib/mysql
volumes:
  mysql: ~
Copy

You can switch between MySQL, PostgreSQL and MongoDB by using the tabs above the code block.

Launch Prisma and the connected database

To start Prisma and launch the connected database, run the following command:

docker-compose up -d
Copy

Prisma is now connected to a local database and runs on http://localhost:4466.

The Prisma server is currently unprotected, meaning everyone with access to its endpoint can send arbitrary requests to it. To secure the Prisma server, you need to set the managementApiSecret property in your Docker Compose file when deploying the server.

When using the Prisma CLI, you then need to set the PRISMA_MANAGEMENT_API_SECRET to the same value so that the CLI can authenticate against the secured server. Learn more here.

Configure your Prisma API

To bootstrap the configuration files for your Prisma client run the following command:

prisma1 init --endpoint http://localhost:4466
Copy

The endpoint needs to match the URL of a running Prisma server.

Deploy the Prisma datamodel

The prisma1 init command created the minimal setup needed to deploy the Prisma datamodel: prisma.yml and datamodel.prisma.

The MongoDB connector uses a new datamodel format than the currently supported SQL databases. The datamodel and prisma.yml need to be configured specifically for MongoDB.

Add the databaseType property to prisma.yml so that it looks as follows:

endpoint: http://localhost:4466
datamodel: datamodel.prisma
databaseType: document
Copy

Now adjust datamodel.prisma to use the new directives:

type User {
  id: ID! @id
  name: String!
}

With these configuration files, you can now deploy the Prisma API:

prisma1 deploy
Copy

Congratulations, you have successfully set up Prisma. You can now start using the Prisma client to talk to your database from code.

View and edit your data in Prisma Admin

If you want to view and edit the data in your database, you can use Prisma Admin. To access Prisma Admin, you need to append /_admin to your Prisma endpoint, for example: http://localhost:4466/_admin.

Generate your Prisma client

The Prisma client is a custom, auto-generated library that connects to your Prisma API. Append the following lines to the end of your prisma.yml:

generate:
  - generator: typescript-client
    output: ./generated/prisma-client/
Copy

Now generate the client with this command:

prisma1 generate
Copy

The CLI now stored your Prisma client inside the ./generated/prisma-client/ directory as specified in prisma.yml.

Prepare TypeScript application

Create your tsconfig.json with the following command:

touch tsconfig.json
Copy

Add the following configuration to the tsconfig.json file:

{
  "compilerOptions": {
    "lib": ["es2016", "esnext.asynciterable"]
  }
}
Copy

Next, initialize an empty NPM project in the current directory and install the required dependencies:

npm init -y
npm install --save prisma-client-lib
npm install --save-dev typescript ts-node
Copy

Almost done! Run the following command to create an empty TypeScript script:

touch index.ts
Copy

Great, you're now ready to write some code and talk to your database programmatically!

Read and write data using the Prisma client

Add the following code in index.ts :

import { prisma } from './generated/prisma-client'

// A `main` function so that we can use async/await
async function main() {
  // Create a new user called `Alice`
  const newUser = await prisma.createUser({ name: 'Alice' })
  console.log(`Created new user: ${newUser.name} (ID: ${newUser.id})`)

  // Read all users from the database and print them to the console
  const allUsers = await prisma.users()
  console.log(allUsers)
}

main().catch(e => console.error(e))
Copy

Before executing the code, go ahead and add a start script to package.json so you can comfortably run the code:

{
  "name": "hello-world",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "ts-node index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "graphql": "^14.0.2",
    "prisma-client-lib": "^1.20.0"
  },
  "devDependencies": {
    "ts-node": "^7.0.1",
    "typescript": "^3.1.6"
  }
}
Copy

Now execute the script with the following command:

npm run start
Copy

Whenever you run the script with that command, a new user record is created in the database (because of the call to createUser).

Feel free to play around with the Prisma client API and try out some of the following operations by adding the following code snippets to the file (at the end of the main function) and re-executing the script:

Fetch single user
Filter user list
Update a user's name
Delete user
const user = await prisma.user({ id: '__USER_ID__' })
Copy

In some snippets, you need to replace the __USER__ID__ placeholder with the ID of an actual user.

Great work! 👏 Move on to learn how you can change your datamodel and (re-)generate your Prisma client.
Next Step