ParsinaBooking API v1

Parsina Booking API

Let a clinic's website or a booking platform show the free times of Parsina clinics and book in-person appointments for patients, all from your server, over REST and JSON.

API base
https://gateway.parsinabot.ir
Version
v1, 2026-11
OpenAPI
/v1/openapi.json
Authentication
OAuth 2.0 client credentials
Caller
Your server only

Introduction

This API is for your website's server, not for a browser. A clinic's website (a WordPress plugin or its own backend), or a booking platform that lists several Parsina clinics, uses it to show free appointment times and to book them.

In these docs a practitioner is anyone a clinic books appointments for: a physician, a dentist, a physiotherapist or a psychologist.

What the API does

  • Returns the clinic's booking profile and the practitioners and services that can be booked online.
  • Lists free times using the same rules as the clinic's own online booking: the practitioner's working hours, days off, the booking window, the minimum lead time and booking pauses.
  • Books an in-person appointment for a patient identified by mobile number and name. The booking is confirmed at once (scheduled) and appears in the clinic's diary marked as coming from a website.
  • Reads and cancels the bookings your own client made.

What it does not do (v1)

  • No prices and no online payment: the visit is paid at the clinic.
  • No SMS to the patient, nor any other message: confirming the booking to your user is your website's job (Notifications).
  • No online (video) visits: in_person only.
  • No rescheduling: to change the time, cancel the booking and book a new one.
  • No webhooks: if the clinic changes or cancels a booking you are not told; read the booking to see its status.
  • No access to patient records: no patient id, no medical data and no other bookings are ever returned.
  • No browser calls: responses carry no CORS headers and a token request from a browser is refused. A website without a backend cannot use this API.
  • No phone verification: there is no one-time code.

Getting access

Credentials are created and managed by the clinic itself in the Parsina clinic panel (clinic.parsinabot.ir); there is no approval and nothing to request from Parsina.

  1. Gold plan. The clinic must be on Parsina's Gold plan (طلایی) with an active subscription that is not read-only; otherwise the screen explains «فقط پلن طلایی» (Gold plan only). If the clinic later leaves Gold or its subscription lapses, the API answers 422 CLINIC_PLAN_REQUIRED for that clinic.
  2. Created in the clinic panel. The clinic's manager, or any staff member holding the «مدیریت اتصال وب‌سایت» (manage website connection) permission, opens «کلینیک من ▸ بیماران ▸ اتصال وب‌سایت / API» (My clinic, Patients, Website connection / API) and chooses «ساخت دسترسی جدید» (new access): a name, the website address, practitioners (all or some), services (all or some), a daily booking cap and, under «پیشرفته» (advanced), an IP allow-list. The access is active at once.
  3. Copied once. The panel shows client_id (prefix pcl_) and client_secret (prefix pcs_) only once; nobody, Parsina included, can see the secret again. The clinic hands both to its website developer over a private channel. If the secret is lost, the clinic makes a new one.

Access settings in the clinic panel

SettingEffect
Practitioners and servicesAll, or only the practitioners and services the clinic picks.
Daily booking cap100 bookings per day on the clinic's calendar by default.
IP allow-list (advanced)Only the website server's IP addresses may call. Recommended.
ScopesEvery access holds all five scopes; the website may ask for fewer when it fetches a token (Authentication).

New secret, pause and revocation

The clinic does all of these on the same panel screen, where the usage report is too.

  • New secret (rotation): the old secret keeps working for 7 days so you can deploy the new one; with the «فوری» (immediate) option it stops at once (after a leak, for example). At most two secrets are valid at a time. Tokens already issued keep working until they expire (15 minutes at most).
  • Pause and resume: within about a minute every call gets 403 CLIENT_PAUSED; bookings already made stay as they are.
  • Revocation: permanent; every secret and token stops working.

One access, one clinic

An access belongs only to the clinic that created it; the token response and GET /v1/me show that one clinic. A booking platform that lists several clinics receives a separate access from each clinic, created by that clinic in its own panel.

Test environment

v1 has a single environment. Every booking you make is a real booking in the clinic's diary: agree a testing time with the clinic and cancel test bookings promptly.

Quick start in 5 steps

Before you start: the clinic creates an access for the website in its panel and gives you client_id and client_secret (Getting access).

The examples use curl and read client_id and client_secret from the environment variables PARSINA_CLIENT_ID and PARSINA_CLIENT_SECRET. Complete programs in other languages are in Full examples.

  1. Get a token.
    curl
    curl -sS https://gateway.parsinabot.ir/oauth/token \
      -u "$PARSINA_CLIENT_ID:$PARSINA_CLIENT_SECRET" \
      -d grant_type=client_credentials

    Keep access_token and a clinic id from clinics. The token is valid for 15 minutes; cache it and use it for every request.

  2. Read the practitioners and services.
    curl
    export TOKEN='pat_…'        # access_token from step 1
    export CLINIC='bc16c5db-ae46-4a03-af3a-515daae06939'   # clinics[0].id from step 1
    
    curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/practitioners" \
      -H "Authorization: Bearer $TOKEN"
    
    curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/services?practitionerId=fb4a5808-15ad-45d9-a57c-41fbf6ea73a1" \
      -H "Authorization: Bearer $TOKEN"
  3. Get the free times.
    curl
    curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/availability?practitionerId=fb4a5808-15ad-45d9-a57c-41fbf6ea73a1&serviceId=38202e35-716e-497a-b15d-bf782de39e02&mode=in_person&from=2026-12-01&days=7" \
      -H "Authorization: Bearer $TOKEN"
  4. Book. Take start exactly from one of the free times. Make one Idempotency-Key per order, store it before the call, and send the same key on every retry.
    curl
    curl -sS -X POST "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/bookings" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      -H "Idempotency-Key: wp-order-88412-1" \
      --data-binary @- <<'JSON'
    {
      "practitionerId": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
      "serviceId": "38202e35-716e-497a-b15d-bf782de39e02",
      "mode": "in_person",
      "start": "2026-12-01T09:00:00+03:30",
      "patient": { "firstName": "سارا", "lastName": "محمدی", "mobile": "09121234567", "relation": "self" },
      "externalRef": "WP-88412"
    }
    JSON
  5. Confirm the booking to your user yourself. Parsina sends no SMS. Show and send the details of the 201 response: Jalali date and time, practitioner, service, clinic address and phone, and the cancellation deadline. Store bookingId with your order.

Authentication

The API uses OAuth 2.0 with the client credentials grant (RFC 6749 §4.4). Your server exchanges client_id and client_secret for an access token and sends it on every /v1 call.

POST /oauth/token

  • Credentials: HTTP Basic (client_id:client_secret), recommended, or the body fields client_id and client_secret.
  • Body: application/x-www-form-urlencoded or JSON, with grant_type=client_credentials.
  • scope (optional): space-separated scopes. Omit it and the token carries every scope of your client; asking only for what you need is better.
HTTP
POST /oauth/token HTTP/1.1
Host: gateway.parsinabot.ir
Authorization: Basic base64(client_id:client_secret)
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&scope=availability%3Aread%20bookings%3Awrite
curl
curl -sS https://gateway.parsinabot.ir/oauth/token \
  -u "$PARSINA_CLIENT_ID:$PARSINA_CLIENT_SECRET" \
  --data-urlencode grant_type=client_credentials \
  --data-urlencode "scope=availability:read bookings:write"

A JSON body is accepted too (with Content-Type: application/json):

JSON
{
  "grant_type": "client_credentials",
  "client_id": "pcl_k7q4m2xw3tbn5hd6yr5f",
  "client_secret": "pcs_…",
  "scope": "availability:read bookings:write"
}

Response 200:

JSON
{
  "access_token": "pat_mLo9CmBaWnTz_7FwYJsJ50wwmCs8R3ewhD680ZT0VQk",
  "token_type": "Bearer",
  "expires_in": 900,
  "scope": "clinic:read availability:read bookings:read bookings:write bookings:cancel",
  "clinics": [
    {
      "id": "bc16c5db-ae46-4a03-af3a-515daae06939",
      "name": "کلینیک تخصصی مهر"
    }
  ]
}

clinics lists the clinics this client may act for. Then send this header on every /v1 call:

HTTP
GET /v1/me HTTP/1.1
Host: gateway.parsinabot.ir
Authorization: Bearer pat_mLo9CmBaWnTz_7FwYJsJ50wwmCs8R3ewhD680ZT0VQk

Scopes

ScopeAllows
clinic:readThe clinic profile, practitioners and services
availability:readFree times
bookings:writeCreating bookings
bookings:readReading the bookings this client made
bookings:cancelCancelling the bookings this client made

GET /v1/me works with any valid token. A token without the scope an endpoint needs gets 403 SCOPE_MISSING.

Caching the token

  • A token is valid for 900 seconds (expires_in), that is 15 minutes. Keep it on the server (memory, Redis, a database row or a WordPress transient) and use it for every request until shortly before it expires; renewing 60 seconds early works well.
  • Do not fetch a token per call: successful token issues are limited to 10 per minute per client_id; failed attempts to 10 per minute per client_id and IP, and 30 per minute per IP. Beyond that the answer is 429 slow_down; keep and reuse the token you have until it expires (900 s).
  • When the credential service is down the answer is 503 temporarily_unavailable with Retry-After: ask again later, and meanwhile keep using the current token if it is still valid.
  • One token covers all of your client's clinics.
  • Never send the token to a browser.

Handling 401 and 403 CLIENT_PAUSED

An expired token gets 401 TOKEN_EXPIRED: drop the cached token, fetch a new one and repeat the request once. Do the same on 401 INVALID_TOKEN. If the new token is refused too, or the token request itself fails with invalid_client or access_denied, do not loop: the clinic may have revoked the access or replaced its secret. Ask the clinic.

An access the clinic has paused in its panel gets 403 CLIENT_PAUSED on /v1 calls (and access_denied from the token endpoint). A new token does not help: stop calling and contact the clinic.

/oauth/token errors

These use the RFC 6749 shape, not the /v1 error shape:

JSON
{
  "error": "invalid_client",
  "error_description": "Client authentication failed."
}
HTTPerrorMeaning
400invalid_requestA parameter is missing or malformed.
400unsupported_grant_typegrant_type is anything but client_credentials.
400invalid_scopeYou asked for a scope your client does not hold.
401invalid_clientWrong client_id or secret, or the secret expired or was revoked. All of these look the same. The response also carries WWW-Authenticate: Basic.
403access_deniedThe client is paused, the request came from an IP outside the allow-list, or it carried a browser Origin header (it was sent from a browser).
429slow_downMore than 10 successful token issues per minute for this client_id, or more than 10 failed attempts per minute for this client_id from this IP, or more than 30 failed attempts per minute from this IP. Keep using the token you have until it expires (900 s).
503temporarily_unavailableThe credential service is temporarily down (with Retry-After). Ask again after that; meanwhile keep using the current token if it is still valid.

Conventions

  • Base URL: https://gateway.parsinabot.ir, HTTPS only.
  • Format: JSON in UTF-8. Send Content-Type: application/json with every body.
  • Request id: every response carries an X-Request-Id header, and errors repeat it as requestId. Keep it in your logs and quote it when you contact Parsina support.
  • Ids: clinic, practitioner, service and booking ids are opaque strings; store them as strings and do not parse them.
  • The clinic is in the path: {clinicId} must be a clinic your client has active access to, otherwise the answer is 403 CLINIC_NOT_GRANTED. The clinic is never read from a request body.
  • Times and dates: see Availability and time zones.
  • Errors: every /v1 error has the same shape and a stable code; message (Persian) and messageEn are for humans and may change. Branch on code (Errors).
  • Forward compatibility: v1 only grows: new fields, endpoints or error codes may appear. Ignore fields you do not know, and handle an unknown error code by its HTTP status.
  • No CORS: browsers cannot call this API, by design.
JSON
{
  "error": {
    "code": "SLOT_TAKEN",
    "message": "این زمان دیگر آزاد نیست.",
    "messageEn": "This time is no longer available.",
    "requestId": "1a47ec46-cb8f-4eab-8e85-5fd8d346677e"
  }
}

Practitioners and services

  • The practitioner list returns the practitioners bookable through your access: active members of the clinic, open for online booking and inside your client's allow-list. serviceIds lists what each one performs. bookingPaused: true means the practitioner has paused online booking for now; show no free times.
  • The service list: id identifies the clinic's service, practitionerIds says who performs it, durationMinutes is the length of one appointment, isDefault marks the clinic's default booking service, and prepInstructions is what the patient should do before coming, to show in your confirmation. prepInstructions may be empty.
  • Every booking names one practitioner; there is no "any free practitioner". To offer "the first free practitioner for service X", get the free times of each practitioner in practitionerIds.
  • serviceId is optional in a booking. Without it the clinic's default service is used, provided this practitioner performs it; otherwise the answer is 400 SERVICE_REQUIRED. Sending serviceId every time is better.
  • A service this practitioner does not offer gets 400 VALIDATION_FAILED with "field": "serviceId". A practitioner whose online booking is closed or paused gets 422 BOOKING_PAUSED or 422 PRACTITIONER_NOT_PRESENT on a booking.
  • 403 PRACTITIONER_NOT_ALLOWED and 403 SERVICE_NOT_ALLOWED mean one thing only: the clinic left this practitioner or service out of this access's allow-list, so your website may not book it. The practitioner and service lists already respect that limit; pick from them.
  • One booking carries one service; the clinic adds any others at the visit.

Availability and time zones

  • Every clinic has its own time zone (timezone, an IANA name): an Iranian clinic is Asia/Tehran, an Iraqi one Asia/Baghdad. Every time returned is ISO 8601 with the clinic's offset, such as 2026-12-01T09:00:00+03:30; the same wall-clock time at a Baghdad clinic is 2026-12-01T09:00:00+03:00.
  • Inputs accept any offset: 2026-12-01T05:30:00Z is the same instant as 2026-12-01T09:00:00+03:30. Compare instants, not strings.
  • Dates (from, date, birthDate, horizonEnd) are Gregorian YYYY-MM-DD, and days are days on the clinic's calendar.
  • Jalali companion: every output with a date also carries jalali: "1405/09/10" on free times and {"date": "1405/09/10", "time": "09:00"} on a booking. Use it to show the date to Persian-speaking users instead of converting yourself, but base your program's logic on the ISO fields.
  • Show times in the clinic's zone, not the visitor's browser zone: the patient travels to the clinic.
  • One availability request covers at most 14 days from from (days from 1 to 14). For later days, ask again with a later from.
  • Free times respect the practitioner's working hours, days off, the minimum lead time (booking.leadTimeMinutes) and the booking horizon (booking.horizonDays, horizonEnd). Each free time lasts the service's duration (durationMinutes).
  • While the practitioner's online booking is paused, the availability answer is still 200, with paused: true and no free time at all. Tell your user that online booking for this practitioner is paused for now.
  • Send only a start taken from the free times, the same instant; the simplest way is to send the free time's start string back unchanged. A start that is not on the slot grid at all (09:07, say) gets 400 VALIDATION_FAILED with "field": "start", and one outside the booking window gets 422 OUT_OF_WINDOW.
  • Free times are a snapshot: after you listed them, another patient may take a time, or the time may vanish from the list. You then get 409 SLOT_TAKEN; refresh the list and let your user choose again (with a new key).

Patients

A patient is identified by mobile number and name. patient.firstName, patient.lastName and patient.mobile are required; gender (male or female), birthDate (Gregorian YYYY-MM-DD) and nationalId are optional.

Mobile number

  • The number is read in the clinic's country. The national form (09121234567 at an Iranian clinic, 07701234567 at an Iraqi one) and the international form (+989121234567) are both accepted; Persian and Arabic digits, spaces and dashes are fine too. We recommend the international form with +.
  • A number that is not a valid mobile number in the clinic's country (in Iran, a landline for example) gets 400 INVALID_MOBILE.
  • Parsina verifies no phone number and sends no one-time code. Checking your users is up to your website, and your client is accountable for the bookings made through it; a client that sends abusive bookings is paused.

Finding or creating the record

  • Parsina looks only among this clinic's patients with that number, for a record with the same first and last name whose birth date and gender do not contradict what you sent. Spelling variants such as Arabic «ي/ك» and Persian «ی/ک», extra spaces and half-spaces count as the same.
  • Exactly one match: the booking goes on that record. None, or more than one: a new record is created and flagged for the clinic's desk, which completes it or merges it with an earlier record when the patient arrives.
  • Parsina never tells you whether the patient already existed. The response is identical in both cases, and the API returns no patient id, no name from Parsina's records and nothing from the medical record. Do not build "welcome back" flows on it.
  • Send names as your user typed them, in Persian script at an Iranian clinic, and leave titles such as «آقای» or «خانم» out of the name.
  • nationalId is used only when a new record is created; it is never used to find a patient.
  • note (at most 500 characters) reaches the clinic as the patient's note; put no more medical detail in it than needed.

relation: whose number it is

relation says who the owner of the mobile number is relative to the patient:

relationWhose number it isExample
self (default)The patient's ownThe patient books for themselves.
parentThe patient's parentA mother books for her child with her own number.
childThe patient's childA son books for his elderly father with his own number.
spouseThe patient's spouseA husband books for his wife with his own number.
siblingThe patient's brother or sisterA sister books for her brother with her own number.
otherAnyone elseA friend or a caregiver.

Why it matters: only self records the number as the patient's own. A relative's number lets the clinic reach the family, but never hands the patient's record to that relative (in the Parsina patient app, for example). Ask "who is this appointment for?" in your form rather than sending self for everyone.

JSON: a mother books for her child
{
  "practitionerId": "7eaa996f-2807-442a-8c40-d9eafa04ba3e",
  "serviceId": "73ebad73-3637-427b-9f13-bef9af031896",
  "start": "2026-12-02T16:00:00+03:30",
  "patient": {
    "firstName": "آرین",
    "lastName": "محمدی",
    "mobile": "09121234567",
    "birthDate": "2019-08-14",
    "relation": "parent"
  },
  "externalRef": "WP-88413"
}

Limits that concern patients

  • At most 5 bookings per mobile number in any 24 hours, across all websites.
  • The clinic's cap on a patient's open bookings: 422 TOO_MANY_OPEN_BOOKINGS.
  • One booking per patient, practitioner and day: 409 DUPLICATE_BOOKING.
  • When the clinic's booking rules refuse the request, the answer is 422 BOOKING_NOT_ALLOWED; it carries no Retry-After and repeating it unchanged does not help. A partner-type client (which v1 does not issue) also gets this code instead of the two above, so that it never learns whether a person has bookings at that clinic.

Idempotency and retries

POST …/bookings and POST …/cancel require an Idempotency-Key header: 8 to 128 characters from A–Z a–z 0–9 . _ : -. Without it, or with a malformed key, the answer is 400 IDEMPOTENCY_KEY_REQUIRED.

  • Make one key per booking attempt (for example wp-order-88412-1, or a UUID), store it with the order before the call, and send the same key and the same body on every retry. Resend exactly the body you sent.
  • A key is unique per client, across all its clinics. Never use one key for another booking.
  • A new attempt with different data (another time after SLOT_TAKEN, a corrected number after INVALID_MOBILE) needs a new key; the old key with a different body gets IDEMPOTENCY_CONFLICT.
SituationAnswer
First request succeeds201 with "replayed": false
Same key and same body, after a success200 with the same booking and "replayed": true, in its current status (cancelled if it was cancelled since)
Same key and same body while the first request is still running409 IN_PROGRESS with Retry-After: 5; wait and repeat the same request
Same key, different body409 IDEMPOTENCY_CONFLICT; never reuse a key for different data
Same key and same body after the first request failedProcessed again as a fresh attempt
Same key and same body after a 503 UNAVAILABLE or a dropped connection200 with "replayed": true if it was booked, otherwise a definite answer (201 or a clear error)

There is no offline queue

While Parsina is unreachable no booking is accepted, and the API does not keep bookings for later. If a request times out, the connection drops or you get 503 UNAVAILABLE, the booking may or may not exist: after Retry-After, send it again with the same key and the same body, and never with a new key. You get either the booking (200 with "replayed": true) or a definite answer. Retrying with the same key never creates a second booking, and a replay is never refused by a rate cap. Meanwhile show your user "booking…", and never say "booked" before you hold a 201 (or a replayed 200).

If several retries still bring no definite answer, keep the key and send the same request again later; meanwhile GET …/bookings?externalRef= tells you whether a booking exists. Never make a new key for the same booking.

HTTP
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Retry-After: 5
X-Request-Id: 1a47ec46-cb8f-4eab-8e85-5fd8d346677e

A 201 that later reads 404

In rare failures, GET or cancel may answer 404 NOT_FOUND for a booking that did get a 201: the record tying the booking to your client is still being written in the background. The API repairs it by itself, usually within a few minutes (also after a restart), so first retry the read a little later. If it still answers 404, repeat the original POST with the same Idempotency-Key and the same body; you get 200 with "replayed": true and the booking. That is why you keep the key and the exact body of every booking you made.

What to retry

AnswerWhat to do
Network error, timeout, 502, 503, 504Resend the same key and the same body with growing waits (Retry-After, otherwise 2, 5, 10, 30 seconds); never with a new key
409 IN_PROGRESSThe same request after Retry-After (5 seconds)
429After Retry-After
401Fetch a new token once and repeat
404 on reading or cancelling a booking that got a 201Repeat the original POST with the same key and body; you get the 200 replay with the booking
Other 4xx, 422 BOOKING_NOT_ALLOWED includedRepeating unchanged does not help: fix the request, or let your user choose again (with a new key)

Cancelling needs a key too, and repeating it with the same key is safe. When unsure, read the booking: a status of cancelled means it is done.

Cancellation

  • Use POST …/bookings/{bookingId}/cancel with an Idempotency-Key header and an optional body {"reason": "…"}.
  • Only bookings this client made; another client's booking gets 404 NOT_FOUND.
  • Cancellation deadline: up to booking.cancelCutoffMinutes minutes before the start (120, for example). Each booking's cancellableUntil is the exact moment; show it to the patient. After it the answer is 422 CANCEL_CUTOFF_PASSED, and the patient must call the clinic (clinic.phone).
  • A booking the clinic has already moved on (checked in, in the visit, completed, no-show) cannot be cancelled through the API.
  • Success is 200 with the booking, "status": "cancelled" and "cancellableUntil": null. The time becomes free and the clinic sees the cancellation. Parsina sends the patient nothing; tell your user yourself.
  • The clinic may cancel a booking too, and v1 has no webhooks: read the booking with GET before sending any reminder.

Notifications: Parsina sends no SMS

  • On success, show the confirmation and send it (by SMS, e-mail or your own app). The 201 response carries everything needed: date and time in the clinic's zone (jalali.date and jalali.time for Persian-speaking users), practitioner.displayName, the service name and its prepInstructions, the clinic's name, address and phone, payment at the clinic, cancellableUntil and how to cancel, and your own reference.
  • Never show "booked" before a 201 (or a replayed 200).
  • Reminders, if you want them, are yours to send; read the booking again shortly before, since the clinic may have cancelled it.
  • The clinic sees the booking in its panel, marked «وب‌سایت» with your client's name.

A sample confirmation (Persian, as the patient would read it):

نوبت شما ثبت شد.
دکتر مریم احمدی، ویزیت متخصص قلب
سه‌شنبه ۱۰ آذر ۱۴۰۵، ساعت ۹:۰۰
کلینیک تخصصی مهر: تهران، خیابان ولیعصر، بالاتر از میدان ونک، کوچهٔ نیلوفر، پلاک ۱۲؛ تلفن ۰۲۱۸۸۷۷۶۶۵۵
هزینه در کلینیک پرداخت می‌شود. اگر نوار قلب یا جواب آزمایش اخیر دارید، همراه بیاورید.
لغو آنلاین تا ۱۰ آذر ساعت ۷:۰۰
کد پیگیری: WP-88412

API reference

Every path is under https://gateway.parsinabot.ir. Every /v1 path needs an Authorization: Bearer … header.

MethodPathScopePurpose
POST/oauth/tokennoneGet a token
GET/v1/meany valid tokenYour client and its clinics
GET/v1/clinics/{clinicId}clinic:readClinic profile
GET/v1/clinics/{clinicId}/practitionersclinic:readPractitioners
GET/v1/clinics/{clinicId}/servicesclinic:readServices
GET/v1/clinics/{clinicId}/availabilityavailability:readFree times
POST/v1/clinics/{clinicId}/bookingsbookings:writeCreate a booking
GET/v1/clinics/{clinicId}/bookings/{bookingId}bookings:readRead a booking
GET/v1/clinics/{clinicId}/bookings?externalRef=bookings:readFind by externalRef
POST/v1/clinics/{clinicId}/bookings/{bookingId}/cancelbookings:cancelCancel a booking
GET/v1/openapi.jsonnoneOpenAPI document

GET /v1/me

Scope: any valid token

Your client, the token's scopes and the clinics you may act for. type is always clinic in v1, and clinics holds that one clinic.

Request

curl
curl -sS "https://gateway.parsinabot.ir/v1/me" \
  -H "Authorization: Bearer $TOKEN"

Response 200

JSON
{
  "client": {
    "clientId": "pcl_k7q4m2xw3tbn5hd6yr5f",
    "name": "وب‌سایت کلینیک مهر",
    "type": "clinic"
  },
  "scopes": [
    "clinic:read",
    "availability:read",
    "bookings:read",
    "bookings:write",
    "bookings:cancel"
  ],
  "clinics": [
    {
      "id": "bc16c5db-ae46-4a03-af3a-515daae06939",
      "name": "کلینیک تخصصی مهر"
    }
  ]
}

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

GET /v1/clinics/{clinicId}

Scope: clinic:read

The clinic's name, address, phone, city, time zone, country and booking rules. booking.enabled: false means the clinic has closed online booking; horizonDays is the booking horizon, leadTimeMinutes the minimum lead time and cancelCutoffMinutes the cancellation deadline before an appointment.

Request

curl
curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC" \
  -H "Authorization: Bearer $TOKEN"

Response 200

JSON
{
  "id": "bc16c5db-ae46-4a03-af3a-515daae06939",
  "name": "کلینیک تخصصی مهر",
  "address": "تهران، خیابان ولیعصر، بالاتر از میدان ونک، کوچهٔ نیلوفر، پلاک ۱۲",
  "phone": "02188776655",
  "city": "تهران",
  "timezone": "Asia/Tehran",
  "country": "IR",
  "booking": {
    "enabled": true,
    "horizonDays": 30,
    "leadTimeMinutes": 60,
    "cancelCutoffMinutes": 120,
    "modes": [
      "in_person"
    ]
  }
}

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

GET /v1/clinics/{clinicId}/practitioners

Scope: clinic:read

The practitioners bookable through your access (Practitioners and services). Show displayName as it is.

Request

curl
curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/practitioners" \
  -H "Authorization: Bearer $TOKEN"

Response 200

JSON
{
  "practitioners": [
    {
      "id": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
      "displayName": "دکتر مریم احمدی",
      "title": "دکتر",
      "specialty": "قلب و عروق",
      "modes": [
        "in_person"
      ],
      "serviceIds": [
        "38202e35-716e-497a-b15d-bf782de39e02",
        "900c7195-b11e-417b-b427-89c43f0f7d9d"
      ],
      "bookingPaused": false
    },
    {
      "id": "7eaa996f-2807-442a-8c40-d9eafa04ba3e",
      "displayName": "دکتر رضا کریمی",
      "title": "دکتر",
      "specialty": "داخلی",
      "modes": [
        "in_person"
      ],
      "serviceIds": [
        "73ebad73-3637-427b-9f13-bef9af031896"
      ],
      "bookingPaused": false
    }
  ]
}

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

GET /v1/clinics/{clinicId}/services

Scope: clinic:read

The services that can be booked online. There is no price field.

Query parameters

ParameterRequiredDescription
practitionerIdnoOnly the services this practitioner performs
modenoin_person

Request

curl
curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/services?practitionerId=fb4a5808-15ad-45d9-a57c-41fbf6ea73a1&mode=in_person" \
  -H "Authorization: Bearer $TOKEN"

Response 200

JSON
{
  "services": [
    {
      "id": "38202e35-716e-497a-b15d-bf782de39e02",
      "name": "ویزیت متخصص قلب",
      "category": "ویزیت",
      "durationMinutes": 20,
      "modes": [
        "in_person"
      ],
      "isDefault": true,
      "practitionerIds": [
        "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1"
      ],
      "prepInstructions": "اگر نوار قلب یا جواب آزمایش اخیر دارید، همراه بیاورید."
    },
    {
      "id": "900c7195-b11e-417b-b427-89c43f0f7d9d",
      "name": "اکوکاردیوگرافی",
      "category": "خدمات تشخیصی",
      "durationMinutes": 30,
      "modes": [
        "in_person"
      ],
      "isDefault": false,
      "practitionerIds": [
        "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1"
      ],
      "prepInstructions": "نیازی به ناشتا بودن نیست."
    }
  ]
}

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

GET /v1/clinics/{clinicId}/availability

Scope: availability:read

A practitioner's free times for one service, day by day (Availability and time zones).

Query parameters

ParameterRequiredDescription
practitionerIdyesThe practitioner
serviceIdnoThe service you intend to book; the slot length comes from its duration. Always send it
modenoin_person
fromalways send itThe first day, YYYY-MM-DD on the clinic's calendar
daysalways send itNumber of days, 1 to 14

Request

curl
curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/availability?practitionerId=fb4a5808-15ad-45d9-a57c-41fbf6ea73a1&serviceId=38202e35-716e-497a-b15d-bf782de39e02&mode=in_person&from=2026-12-01&days=2" \
  -H "Authorization: Bearer $TOKEN"

Response 200

JSON
{
  "timezone": "Asia/Tehran",
  "durationMinutes": 20,
  "horizonEnd": "2026-12-28",
  "paused": false,
  "days": [
    {
      "date": "2026-12-01",
      "jalali": "1405/09/10",
      "slots": [
        {
          "start": "2026-12-01T09:00:00+03:30",
          "end": "2026-12-01T09:20:00+03:30"
        },
        {
          "start": "2026-12-01T09:20:00+03:30",
          "end": "2026-12-01T09:40:00+03:30"
        },
        {
          "start": "2026-12-01T10:20:00+03:30",
          "end": "2026-12-01T10:40:00+03:30"
        }
      ]
    },
    {
      "date": "2026-12-02",
      "jalali": "1405/09/11",
      "slots": [
        {
          "start": "2026-12-02T16:00:00+03:30",
          "end": "2026-12-02T16:20:00+03:30"
        }
      ]
    }
  ]
}

Response fields

FieldDescription
timezoneThe clinic's time zone
durationMinutesThe length of each free time, i.e. the service's duration
horizonEndThe last day that can be booked now
pausedtrue means the practitioner's online booking is paused; the answer is still 200 and carries no free time
daysDays with date, jalali and slots (start and end)

A paused practitioner is not an error: the answer is 200 with paused: true. This endpoint never answers 422 BOOKING_DISABLED.

Specific errors

  • 400 VALIDATION_FAILED a bad parameter, such as days outside 1 to 14, or "field": "serviceId" for a service this practitioner does not offer
  • 403 PRACTITIONER_NOT_ALLOWED the practitioner is outside this access's allow-list
  • 403 SERVICE_NOT_ALLOWED the service is outside this access's allow-list
  • 422 MODE_NOT_AVAILABLE

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

POST /v1/clinics/{clinicId}/bookings

Scope: bookings:write

Books an in-person appointment. The Idempotency-Key header is required (Idempotency). The booking is scheduled at once.

Body

FieldTypeRequiredDescription
practitionerIdstringyesFrom practitioners
serviceIdstringnoFrom services, and one this practitioner offers (else VALIDATION_FAILED with field serviceId); without it the clinic's default service, provided this practitioner performs it, otherwise SERVICE_REQUIRED
modestringnoin_person, the only value in v1
startstring (ISO 8601)yesOnly the start of one of the free times, the same instant; any offset. A time off the slot grid gets VALIDATION_FAILED with field start
patient.firstNamestringyesFirst name
patient.lastNamestringyesLast name
patient.mobilestringyesSee Patients
patient.genderstringnomale or female
patient.birthDatestring (YYYY-MM-DD)noGregorian
patient.nationalIdstringnoNever used to find a patient
patient.relationstringnoself (default), child, spouse, parent, sibling, other: the number's owner relative to the patient
notestring, at most 500noThe patient's note for the clinic
externalRefstring, at most 128noYour own order number or reference; used to look bookings up
JSON: booking.json
{
  "practitionerId": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
  "serviceId": "38202e35-716e-497a-b15d-bf782de39e02",
  "mode": "in_person",
  "start": "2026-12-01T09:00:00+03:30",
  "patient": {
    "firstName": "سارا",
    "lastName": "محمدی",
    "mobile": "09121234567",
    "gender": "female",
    "birthDate": "1990-05-01",
    "nationalId": "0012345679",
    "relation": "self"
  },
  "note": "تنگی نفس هنگام فعالیت از دو هفته پیش",
  "externalRef": "WP-88412"
}

The shortest possible request (the clinic's default service):

JSON
{
  "practitionerId": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
  "start": "2026-12-01T09:20:00+03:30",
  "patient": {
    "firstName": "علی",
    "lastName": "رضایی",
    "mobile": "+989351112233"
  }
}

Request

curl
curl -sS -X POST "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/bookings" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: wp-order-88412-1" \
  --data-binary @booking.json

Response 201

JSON
{
  "bookingId": "4043f855-991c-4ce1-8179-2387d1a0c0e4",
  "status": "scheduled",
  "start": "2026-12-01T09:00:00+03:30",
  "end": "2026-12-01T09:20:00+03:30",
  "timezone": "Asia/Tehran",
  "jalali": {
    "date": "1405/09/10",
    "time": "09:00"
  },
  "practitioner": {
    "id": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
    "displayName": "دکتر مریم احمدی"
  },
  "service": {
    "id": "38202e35-716e-497a-b15d-bf782de39e02",
    "name": "ویزیت متخصص قلب"
  },
  "mode": "in_person",
  "payment": {
    "method": "at_clinic"
  },
  "cancellableUntil": "2026-12-01T07:00:00+03:30",
  "clinic": {
    "id": "bc16c5db-ae46-4a03-af3a-515daae06939",
    "name": "کلینیک تخصصی مهر",
    "address": "تهران، خیابان ولیعصر، بالاتر از میدان ونک، کوچهٔ نیلوفر، پلاک ۱۲",
    "phone": "02188776655"
  },
  "externalRef": "WP-88412",
  "createdAt": "2026-11-28T14:05:12+03:30",
  "replayed": false
}

Repeating the same request with the same key gets 200 and the same booking with "replayed": true. After a 503 UNAVAILABLE the outcome may be unknown: repeat with the same key after Retry-After, never with a new key (Idempotency).

The booking object

FieldDescription
bookingIdThe booking id
statusscheduled booked and confirmed · arrived checked in · in_visit being seen · completed finished · cancelled cancelled · no_show the patient did not come
start, end, timezoneThe appointment time in the clinic's zone
jalaliJalali date and time, for display
practitionerid and displayName
serviceid and name; may be null
modein_person when booked; it may later read online if the clinic converts the visit
payment{"method": "at_clinic"}: paid at the clinic. No price is returned
cancellableUntilThe last moment for an online cancellation; null once cancelled
clinicid, name, address, phone
externalRef, createdAtYour reference and when it was booked
replayedOnly on the create response: false for a new booking, true for a replay

Specific errors

  • 400 VALIDATION_FAILED a field is missing or invalid; field names it, e.g. serviceId for a service this practitioner does not offer, or start for a time off the slot grid
  • 400 SERVICE_REQUIRED
  • 400 INVALID_MOBILE
  • 400 IDEMPOTENCY_KEY_REQUIRED
  • 403 PRACTITIONER_NOT_ALLOWED the practitioner is outside this access's allow-list
  • 403 SERVICE_NOT_ALLOWED the service is outside this access's allow-list
  • 409 SLOT_TAKEN the time was taken, or vanished, since you listed it
  • 409 DUPLICATE_BOOKING
  • 409 IDEMPOTENCY_CONFLICT
  • 409 IN_PROGRESS
  • 422 BOOKING_DISABLED
  • 422 BOOKING_PAUSED the practitioner's online booking is paused or closed
  • 422 OUT_OF_WINDOW
  • 422 PRACTITIONER_NOT_PRESENT the practitioner is not working then, or is closed to online booking
  • 422 SERVICE_NOT_IN_SHIFT
  • 422 MODE_NOT_AVAILABLE
  • 422 TOO_MANY_OPEN_BOOKINGS
  • 422 BOOKING_NOT_ALLOWED the clinic's booking rules refused it; no Retry-After, do not retry unchanged
  • 503 UNAVAILABLE the outcome may be unknown; repeat with the same key
JSON
{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "تاریخ تولد معتبر نیست.",
    "messageEn": "birthDate is not a valid date.",
    "field": "patient.birthDate",
    "requestId": "1a47ec46-cb8f-4eab-8e85-5fd8d346677e"
  }
}

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

GET /v1/clinics/{clinicId}/bookings/{bookingId}

Scope: bookings:read

One of this client's bookings, in its current state. Another client's booking, or one made at the desk or in an app, gets 404 NOT_FOUND.

Request

curl
curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/bookings/4043f855-991c-4ce1-8179-2387d1a0c0e4" \
  -H "Authorization: Bearer $TOKEN"

Response 200

JSON
{
  "bookingId": "4043f855-991c-4ce1-8179-2387d1a0c0e4",
  "status": "scheduled",
  "start": "2026-12-01T09:00:00+03:30",
  "end": "2026-12-01T09:20:00+03:30",
  "timezone": "Asia/Tehran",
  "jalali": {
    "date": "1405/09/10",
    "time": "09:00"
  },
  "practitioner": {
    "id": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
    "displayName": "دکتر مریم احمدی"
  },
  "service": {
    "id": "38202e35-716e-497a-b15d-bf782de39e02",
    "name": "ویزیت متخصص قلب"
  },
  "mode": "in_person",
  "payment": {
    "method": "at_clinic"
  },
  "cancellableUntil": "2026-12-01T07:00:00+03:30",
  "clinic": {
    "id": "bc16c5db-ae46-4a03-af3a-515daae06939",
    "name": "کلینیک تخصصی مهر",
    "address": "تهران، خیابان ولیعصر، بالاتر از میدان ونک، کوچهٔ نیلوفر، پلاک ۱۲",
    "phone": "02188776655"
  },
  "externalRef": "WP-88412",
  "createdAt": "2026-11-28T14:05:12+03:30"
}

Specific errors

  • 404 NOT_FOUND if you received a 201 for this booking, repeat the original POST with the same Idempotency-Key and body to get the 200 replay with the booking (Idempotency)

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

GET /v1/clinics/{clinicId}/bookings?externalRef=

Scope: bookings:read

This client's bookings at this clinic with that externalRef, newest first. Useful when the answer to a booking request was lost. With no match the list is empty.

Query parameters

ParameterRequiredDescription
externalRefyesThe value you sent when booking

Request

curl
curl -sS "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/bookings?externalRef=WP-88412" \
  -H "Authorization: Bearer $TOKEN"

Response 200

JSON
{
  "bookings": [
    {
      "bookingId": "4043f855-991c-4ce1-8179-2387d1a0c0e4",
      "status": "scheduled",
      "start": "2026-12-01T09:00:00+03:30",
      "end": "2026-12-01T09:20:00+03:30",
      "timezone": "Asia/Tehran",
      "jalali": {
        "date": "1405/09/10",
        "time": "09:00"
      },
      "practitioner": {
        "id": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
        "displayName": "دکتر مریم احمدی"
      },
      "service": {
        "id": "38202e35-716e-497a-b15d-bf782de39e02",
        "name": "ویزیت متخصص قلب"
      },
      "mode": "in_person",
      "payment": {
        "method": "at_clinic"
      },
      "cancellableUntil": "2026-12-01T07:00:00+03:30",
      "clinic": {
        "id": "bc16c5db-ae46-4a03-af3a-515daae06939",
        "name": "کلینیک تخصصی مهر",
        "address": "تهران، خیابان ولیعصر، بالاتر از میدان ونک، کوچهٔ نیلوفر، پلاک ۱۲",
        "phone": "02188776655"
      },
      "externalRef": "WP-88412",
      "createdAt": "2026-11-28T14:05:12+03:30"
    }
  ]
}

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

POST /v1/clinics/{clinicId}/bookings/{bookingId}/cancel

Scope: bookings:cancel

Cancels one of this client's bookings before cancellableUntil (Cancellation). The Idempotency-Key header is required; the body is optional.

Body

JSON
{
  "reason": "بیمار در آن روز در سفر است."
}

Request

curl
curl -sS -X POST "https://gateway.parsinabot.ir/v1/clinics/$CLINIC/bookings/4043f855-991c-4ce1-8179-2387d1a0c0e4/cancel" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: wp-order-88412-cancel" \
  -d '{"reason": "بیمار در آن روز در سفر است."}'

Response 200

JSON
{
  "bookingId": "4043f855-991c-4ce1-8179-2387d1a0c0e4",
  "status": "cancelled",
  "start": "2026-12-01T09:00:00+03:30",
  "end": "2026-12-01T09:20:00+03:30",
  "timezone": "Asia/Tehran",
  "jalali": {
    "date": "1405/09/10",
    "time": "09:00"
  },
  "practitioner": {
    "id": "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1",
    "displayName": "دکتر مریم احمدی"
  },
  "service": {
    "id": "38202e35-716e-497a-b15d-bf782de39e02",
    "name": "ویزیت متخصص قلب"
  },
  "mode": "in_person",
  "payment": {
    "method": "at_clinic"
  },
  "cancellableUntil": null,
  "clinic": {
    "id": "bc16c5db-ae46-4a03-af3a-515daae06939",
    "name": "کلینیک تخصصی مهر",
    "address": "تهران، خیابان ولیعصر، بالاتر از میدان ونک، کوچهٔ نیلوفر، پلاک ۱۲",
    "phone": "02188776655"
  },
  "externalRef": "WP-88412",
  "createdAt": "2026-11-28T14:05:12+03:30"
}

Specific errors

  • 400 IDEMPOTENCY_KEY_REQUIRED
  • 404 NOT_FOUND for a booking that got a 201: first repeat the original POST with the same key and body, then cancel again
  • 422 CANCEL_CUTOFF_PASSED
JSON
{
  "error": {
    "code": "CANCEL_CUTOFF_PASSED",
    "message": "مهلت لغو آنلاین این نوبت گذشته است.",
    "messageEn": "The online cancellation deadline has passed.",
    "requestId": "1a47ec46-cb8f-4eab-8e85-5fd8d346677e"
  }
}

The general errors (401, 403 SCOPE_MISSING, 403 CLINIC_NOT_GRANTED, 422 CLINIC_PLAN_REQUIRED, 429, 503) are in Errors.

GET /v1/openapi.json

The machine-readable description of this API, no token needed: https://gateway.parsinabot.ir/v1/openapi.json. Generate a client from it or import the requests into tools such as Postman.

curl
curl -sS https://gateway.parsinabot.ir/v1/openapi.json -o parsina-booking-api.json

GET /healthz on the same host, without a token, tells you whether the service is up.

Errors

Every /v1 error has this shape. field is present only when the error concerns one field. /oauth/token errors have a different shape (Authentication).

JSON
{
  "error": {
    "code": "VALIDATION_FAILED",
    "message": "تاریخ تولد معتبر نیست.",
    "messageEn": "birthDate is not a valid date.",
    "field": "patient.birthDate",
    "requestId": "1a47ec46-cb8f-4eab-8e85-5fd8d346677e"
  }
}
HTTPCodeMeaningWhat to do
400VALIDATION_FAILEDA field is missing or invalid; field names it. Among others "field": "serviceId" for a service this practitioner does not offer, and "field": "start" for a time that is not on the slot grid at all (09:07, say).Fix the request and tell your user which field; take start only from the free times. Do not retry unchanged.
400SERVICE_REQUIREDNo serviceId, and this practitioner does not perform the clinic's default service.Send a serviceId from the service list.
400INVALID_MOBILEThe number is not a valid mobile number in the clinic's country.Ask your user to correct it; send the international form (+98…).
400IDEMPOTENCY_KEY_REQUIREDThe Idempotency-Key header is missing or malformed.Send a key of 8 to 128 allowed characters.
401INVALID_TOKENThe token is missing, unknown or revoked (after the clinic revoked the access, for example).Fetch a new token once and repeat; if refused again, ask the clinic.
401TOKEN_EXPIREDThe token's 15 minutes are over.Fetch a new token and repeat.
403SCOPE_MISSINGThe token lacks the scope this endpoint needs.Fetch the token without scope, or with this scope.
403CLINIC_NOT_GRANTEDYour client has no active access to this clinic.Take the clinic id from /v1/me; an access holds only the clinic that created it.
403CLIENT_PAUSEDThe clinic has paused your access in its panel.Stop calling and ask the clinic.
403PRACTITIONER_NOT_ALLOWEDThis practitioner is outside this access's allow-list: the clinic limited which practitioners your website may book. (A practitioner closed to online booking gets BOOKING_PAUSED or PRACTITIONER_NOT_PRESENT instead.)Offer only practitioners from the practitioner list; to add one, the clinic widens the allow-list in its panel.
403SERVICE_NOT_ALLOWEDThis service is outside this access's allow-list: the clinic limited which services your website may book. (A service this practitioner does not offer gets VALIDATION_FAILED instead.)Offer only services from the service list; to add one, the clinic widens the allow-list in its panel.
403IP_NOT_ALLOWEDThe request came from an IP outside your allow-list.Call from an allowed server, or ask the clinic to update the list in its panel.
404NOT_FOUNDNo such resource; another client's booking gets this answer too.Check the id and the clinic. If you received a 201 for this booking, repeat the original POST with the same Idempotency-Key and body to get it back.
409SLOT_TAKENThe time was taken, or has vanished from the free times, since you listed it.Refresh the free times, let your user choose again and send with a new key.
409DUPLICATE_BOOKINGThe patient already has a booking with this practitioner that day.Tell your user; do not retry.
409IDEMPOTENCY_CONFLICTThis key was already used with a different request.Use a new key for a new request; to replay, resend the original body.
409IN_PROGRESSA request with this key is still running (Retry-After: 5).Repeat the same request after Retry-After.
422BOOKING_DISABLEDThe clinic has closed online booking.Hide booking for this clinic (booking.enabled).
422BOOKING_PAUSEDThe practitioner's online booking is paused or closed.Offer another practitioner or a later time.
422OUT_OF_WINDOWThe time is outside the booking window (sooner than the lead time or beyond the horizon).Take the time from the free times.
422PRACTITIONER_NOT_PRESENTThe practitioner is not working at that time (shift or day off), or is closed to online booking.Take the time from the free times, or offer another practitioner.
422SERVICE_NOT_IN_SHIFTThe service is not offered in the practitioner's shift at that time.Get the free times for this service.
422MODE_NOT_AVAILABLEThis visit mode is not available; v1 is in-person only.Send "mode": "in_person".
422TOO_MANY_OPEN_BOOKINGSThe patient has reached the clinic's cap on open bookings.Tell your user to attend or cancel an earlier booking, or to call the clinic.
422CANCEL_CUTOFF_PASSEDThe online cancellation deadline (cancellableUntil) has passed.Ask the patient to call the clinic.
422CLINIC_UNAVAILABLEThe clinic is not taking bookings through the API right now (it is inactive, for example).Hide booking and check again later, or contact the clinic.
422CLINIC_PLAN_REQUIREDThe clinic is not on the Gold plan, or its subscription is read-only or expired.Hide booking; the clinic must renew or upgrade with Parsina.
422BOOKING_NOT_ALLOWEDThe clinic's booking rules refused this request. It carries no Retry-After. A partner-type client (which v1 does not issue) also gets it instead of DUPLICATE_BOOKING and TOO_MANY_OPEN_BOOKINGS.Do not retry unchanged; ask your user to contact the clinic.
429RATE_LIMITEDToo many requests (Retry-After). A replay of an earlier request is never refused by a rate cap.Wait Retry-After seconds and slow down.
503UNAVAILABLEParsina is temporarily unavailable (Retry-After). On a booking the outcome may be unknown.Repeat after Retry-After with the same Idempotency-Key and the same body, never a new key: you get the booking (a 200 replay) or a definite answer.

Handle an unknown code by its HTTP status: a 4xx means the request must change, a 5xx means repeat later with the same key. Quote requestId when you contact support.

Rate limits

WhatLimitBeyond it
Token requestsSuccessful issues: 10 per minute per client_id; failed attempts: 10 per minute per client_id and IP, and 30 per minute per IP429 slow_down
Reads (GET /v1/…)600 per minute per client429 RATE_LIMITED
Bookings and cancellations60 per hour per client (booking attempts and cancels actually made)429 RATE_LIMITED
Bookings per clinic per dayThe cap the clinic set on the access (100 by default), per day on the clinic's calendar429 RATE_LIMITED
Bookings per mobile number5 in any 24 hours, across all websites429 RATE_LIMITED
A patient's open bookingsThe clinic's own cap422 TOO_MANY_OPEN_BOOKINGS
Per patient, practitioner and dayOne booking409 DUPLICATE_BOOKING
  • Always honour Retry-After; the numbers may change.
  • The write budget (60 per hour) is a rate of attempts: it counts each booking attempt the API actually tries and each cancel actually sent, and a booking the clinic's schedule refuses at the booking step itself (a 409 or 422 from that step) still counts. A booking refused before that step — a validation error, a practitioner or service error, or a start no longer in availability — does not count. A 429 from the clinic's daily cap or the per-mobile limit does not count, and replays, IN_PROGRESS and idempotency conflicts (IDEMPOTENCY_CONFLICT) never count.
  • A replay of a booking, with the same Idempotency-Key and the same body, is never refused by a rate cap; after a 503 or a dropped connection, repeat with the same key without worry.
  • On 429 slow_down from the token endpoint, keep using the token you have until it expires (900 s).
  • Practitioners, services and the clinic profile change rarely: cache them on your server for a few minutes. Fetch free times fresh.
  • Very high request rates from one IP are also limited before they reach the API; such an answer (429 or 503) may carry no JSON body. Act on the status code and retry with a delay.

Security checklist

  • client_secret lives on the server only: in an environment variable or a secret store, never in browser JavaScript, a mobile app, a code repository, a log, a ticket or a chat.
  • The API is called from your server only. A browser request (with an Origin header) is refused and there is no CORS.
  • The token is kept on the server and never reaches a browser.
  • HTTPS only, with certificate verification; never switch TLS verification off.
  • The clinic has set the IP allow-list (advanced) to your server's outgoing IP addresses.
  • You ask only for the scopes you need.
  • Your booking form is protected against bots and abuse (a captcha, rate limits, your own user checks), because Parsina verifies no phone numbers and your client is accountable for its bookings.
  • Full mobile numbers and patient names stay out of your logs; mask numbers (keep the last 4 digits, for example).
  • No patient data (name, number, national id) in externalRef or Idempotency-Key; they are identifiers.
  • Your logs keep the X-Request-Id of responses.
  • If the secret leaks, the clinic makes a new secret at once in its panel, with the immediate option.

Full examples

Each example is a complete flow: a cached token, free times, a booking with safe retries and the confirmation to the user. The credentials are read from the environment variables PARSINA_CLIENT_ID and PARSINA_CLIENT_SECRET.

curl and jq

The whole flow in one bash script with curl and jq.

bash
#!/usr/bin/env bash
# The whole flow with curl + jq: token, catalogue, free times, booking, read, cancel.
# Run it on your SERVER. PARSINA_CLIENT_ID / PARSINA_CLIENT_SECRET come from the
# environment, never from a file in your web root.
set -euo pipefail
API=https://gateway.parsinabot.ir

# 1. Token: valid 900 s. Real code caches it and reuses it for every call.
TOKEN=$(curl -sS -u "$PARSINA_CLIENT_ID:$PARSINA_CLIENT_SECRET" \
  -d grant_type=client_credentials "$API/oauth/token" | jq -r .access_token)
auth=(-H "Authorization: Bearer $TOKEN")

# 2. The clinic this client may book for, its practitioners and services.
CLINIC=$(curl -sS "${auth[@]}" "$API/v1/me" | jq -r '.clinics[0].id')
curl -sS "${auth[@]}" "$API/v1/clinics/$CLINIC/practitioners" | jq '.practitioners[] | {id, displayName}'
PRACTITIONER=fb4a5808-15ad-45d9-a57c-41fbf6ea73a1
SERVICE=38202e35-716e-497a-b15d-bf782de39e02

# 3. Free times for one week; take the first one.
START=$(curl -sS "${auth[@]}" \
  "$API/v1/clinics/$CLINIC/availability?practitionerId=$PRACTITIONER&serviceId=$SERVICE&mode=in_person&from=2026-12-01&days=7" \
  | jq -r '[.days[].slots[]][0].start')

# 4. Book. One Idempotency-Key per order; a retry re-sends the SAME key and body.
KEY="wp-order-88412-1"
jq -n --arg p "$PRACTITIONER" --arg s "$SERVICE" --arg t "$START" '{
  practitionerId: $p, serviceId: $s, mode: "in_person", start: $t,
  patient: { firstName: "سارا", lastName: "محمدی", mobile: "09121234567", relation: "self" },
  externalRef: "WP-88412"
}' > booking.json
for wait in 0 2 5 10 30; do
  sleep "$wait"
  status=$(curl -sS -o booking-response.json -w '%{http_code}' -X POST \
    "${auth[@]}" -H "Content-Type: application/json" -H "Idempotency-Key: $KEY" \
    --data-binary @booking.json "$API/v1/clinics/$CLINIC/bookings") || status=000
  case "$status" in
    200|201) break ;;               # booked (200 = replay of the same request)
    000|429|5??) continue ;;        # no answer, rate limit, outage: the same key again
    409) [ "$(jq -r .error.code booking-response.json)" = IN_PROGRESS ] && continue
         jq . booking-response.json; exit 1 ;;   # SLOT_TAKEN etc.: ask the user, new key
    *) jq . booking-response.json; exit 1 ;;
  esac
done
# Still no definite answer: retry later with the SAME key (never a new one); GET ?externalRef= shows it.
jq -e '.bookingId' booking-response.json > /dev/null || { jq . booking-response.json; exit 1; }
BOOKING=$(jq -r .bookingId booking-response.json)

# 5. Parsina sends no SMS: confirm to the patient yourself.
jq -r '"نوبت ثبت شد: \(.jalali.date) ساعت \(.jalali.time) — \(.practitioner.displayName)، \(.clinic.name)"' booking-response.json

# Later: read it, or cancel it before cancellableUntil.
curl -sS "${auth[@]}" "$API/v1/clinics/$CLINIC/bookings/$BOOKING" | jq '{status, cancellableUntil}'
curl -sS -X POST "${auth[@]}" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $KEY-cancel" -d '{"reason": "بیمار منصرف شد."}' \
  "$API/v1/clinics/$CLINIC/bookings/$BOOKING/cancel" | jq .status

PHP (curl extension, no Guzzle)

PHP 7.4 or later with the curl extension; no Composer. The token is cached in a temporary file readable by this user only; in WordPress a transient works as well.

PHP
<?php
// Parsina Booking API client: PHP 7.4+ with the curl extension, no Composer packages.
// Server side only. The secret comes from the environment, never from a page.

final class ParsinaNetworkError extends RuntimeException {}

final class ParsinaApiError extends RuntimeException
{
    public int $status;
    public string $apiCode;
    public string $requestId;

    public function __construct(int $status, array $body)
    {
        $e = $body['error'] ?? [];
        if (is_string($e)) { // /oauth/token answers in the RFC 6749 shape
            $e = ['code' => $e, 'messageEn' => $body['error_description'] ?? ''];
        }
        $this->status = $status;
        $this->apiCode = (string) ($e['code'] ?? 'HTTP_' . $status);
        $this->requestId = (string) ($e['requestId'] ?? '');
        parent::__construct(($e['messageEn'] ?? 'request failed') . ' [' . $this->apiCode . ']');
    }
}

final class ParsinaBooking
{
    private const API = 'https://gateway.parsinabot.ir';
    private string $clientId;
    private string $clientSecret;
    private string $cacheFile;

    public function __construct(string $clientId, string $clientSecret)
    {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->cacheFile = sys_get_temp_dir() . '/parsina-token-' . hash('sha256', $clientId) . '.json';
    }

    /** The cached access token, renewed 60 s before it expires. */
    private function token(bool $forceNew = false): string
    {
        if (!$forceNew && is_readable($this->cacheFile)) {
            $cached = json_decode((string) file_get_contents($this->cacheFile), true);
            if (is_array($cached) && ($cached['expires_at'] ?? 0) > time() + 60) {
                return $cached['access_token'];
            }
        }
        [$status, $body] = $this->send('POST', '/oauth/token',
            ['Content-Type: application/x-www-form-urlencoded'],
            http_build_query(['grant_type' => 'client_credentials']), true);
        if ($status !== 200) {
            throw new ParsinaApiError($status, $body);
        }
        $old = umask(0077); // the token file is readable by this user only
        file_put_contents($this->cacheFile, json_encode([
            'access_token' => $body['access_token'],
            'expires_at'   => time() + (int) $body['expires_in'],
        ]), LOCK_EX);
        umask($old);
        return $body['access_token'];
    }

    /** @return array{0:int,1:array,2:array} status, decoded body, lower-cased headers */
    private function send(string $method, string $path, array $headers, ?string $payload, bool $basic = false): array
    {
        $responseHeaders = [];
        $ch = curl_init(self::API . $path);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER     => array_merge(['Accept: application/json'], $headers),
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$responseHeaders): int {
                $parts = explode(':', $line, 2);
                if (count($parts) === 2) {
                    $responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
                }
                return strlen($line);
            },
        ]);
        if ($payload !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        }
        if ($basic) {
            curl_setopt($ch, CURLOPT_USERPWD, $this->clientId . ':' . $this->clientSecret);
        }
        $raw = curl_exec($ch);
        if ($raw === false) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new ParsinaNetworkError($error);
        }
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        curl_close($ch);
        return [$status, json_decode($raw, true) ?? [], $responseHeaders];
    }

    /** One /v1 call. Renews the token once when the API answers 401. */
    public function call(string $method, string $path, ?array $json = null, ?string $idempotencyKey = null): array
    {
        $headers = [];
        $payload = null;
        if ($json !== null) {
            $headers[] = 'Content-Type: application/json';
            $payload = json_encode($json, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
        }
        if ($idempotencyKey !== null) {
            $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
        }
        $response = [];
        for ($attempt = 0; $attempt < 2; $attempt++) {
            $bearer = 'Authorization: Bearer ' . $this->token($attempt > 0);
            $response = $this->send($method, $path, array_merge($headers, [$bearer]), $payload);
            if ($response[0] !== 401) {
                break;
            }
        }
        return $response;
    }

    /** GET that throws on anything but 200. */
    public function get(string $path): array
    {
        [$status, $body] = $this->call('GET', $path);
        if ($status !== 200) {
            throw new ParsinaApiError($status, $body);
        }
        return $body;
    }

    /**
     * Books with retries that can never double-book: the same key and the same
     * body every time. Returns the booking or throws ParsinaApiError.
     */
    public function book(string $clinicId, array $booking, string $idempotencyKey): array
    {
        $backoff = [2, 5, 10, 30];
        for ($attempt = 0; ; $attempt++) {
            $wait = null;
            try {
                [$status, $body, $headers] = $this->call('POST', "/v1/clinics/$clinicId/bookings", $booking, $idempotencyKey);
                if ($status === 201 || $status === 200) {
                    return $body; // 200 = a replay of the same request
                }
                $retryable = $status === 429 || $status >= 500 || ($body['error']['code'] ?? '') === 'IN_PROGRESS';
                if (!$retryable) {
                    throw new ParsinaApiError($status, $body);
                }
                $wait = isset($headers['retry-after']) ? (int) $headers['retry-after'] : null;
            } catch (ParsinaNetworkError $e) {
                // Timeout or no connection: the outcome is unknown, so retry the SAME key.
            } catch (ParsinaApiError $e) {
                if ($e->status < 500) {
                    throw $e; // a definite refusal; a 5xx (token 503 included) is retried
                }
            }
            if ($attempt >= count($backoff)) {
                throw new RuntimeException('No definite answer yet. Retry later with the SAME key; never a new one.');
            }
            sleep(min($wait ?? $backoff[$attempt], 60));
        }
    }
}

// ── Usage ───────────────────────────────────────────────────────────────────
$api = new ParsinaBooking(getenv('PARSINA_CLIENT_ID'), getenv('PARSINA_CLIENT_SECRET'));
$clinicId = 'bc16c5db-ae46-4a03-af3a-515daae06939';
$practitionerId = 'fb4a5808-15ad-45d9-a57c-41fbf6ea73a1';
$serviceId = '38202e35-716e-497a-b15d-bf782de39e02';

$availability = $api->get("/v1/clinics/$clinicId/availability?" . http_build_query([
    'practitionerId' => $practitionerId,
    'serviceId'      => $serviceId,
    'mode'           => 'in_person',
    'from'           => '2026-12-01',
    'days'           => 7,
]));
$slots = array_merge([], ...array_column($availability['days'], 'slots'));
if (!$slots) {
    exit("No free time in this range.\n");
}

$booking = $api->book($clinicId, [
    'practitionerId' => $practitionerId,
    'serviceId'      => $serviceId,
    'mode'           => 'in_person',
    'start'          => $slots[0]['start'],
    'patient'        => [
        'firstName' => 'سارا',
        'lastName'  => 'محمدی',
        'mobile'    => '09121234567',
        'relation'  => 'self',
    ],
    'externalRef'    => 'WP-88412',
], 'wp-order-88412-1');

// Parsina sends no SMS: confirm to the patient yourself (on screen, SMS, e-mail).
printf("نوبت ثبت شد: %s ساعت %s — %s، %s\n",
    $booking['jalali']['date'], $booking['jalali']['time'],
    $booking['practitioner']['displayName'], $booking['clinic']['name']);

Node.js (fetch)

Node.js 18 or later with the built-in fetch; no packages. Save it as book.mjs.

Node.js
// Parsina Booking API client: Node.js 18+ (built-in fetch), no packages.
// Save as book.mjs. Server side only: the secret must never reach a browser.
const API = 'https://gateway.parsinabot.ir';
const { PARSINA_CLIENT_ID, PARSINA_CLIENT_SECRET } = process.env;

export class ParsinaError extends Error {
  constructor(status, body) {
    // /oauth/token answers in the RFC 6749 shape, /v1 in { error: { code, … } }
    const e = typeof body?.error === 'string'
      ? { code: body.error, messageEn: body.error_description }
      : body?.error ?? {};
    super(`${e.code ?? `HTTP_${status}`}: ${e.messageEn ?? 'request failed'}`);
    this.status = status;
    this.code = e.code;
    this.requestId = e.requestId;
  }
}

let cached = null; // { token, expiresAt }: one token for every call, renewed 60 s early

async function getToken(forceNew = false) {
  if (!forceNew && cached && cached.expiresAt - 60_000 > Date.now()) return cached.token;
  const res = await fetch(`${API}/oauth/token`, {
    method: 'POST',
    headers: {
      Authorization: 'Basic ' + Buffer.from(`${PARSINA_CLIENT_ID}:${PARSINA_CLIENT_SECRET}`).toString('base64'),
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({ grant_type: 'client_credentials' }),
    signal: AbortSignal.timeout(10_000),
  });
  const body = await res.json().catch(() => null);
  if (!res.ok) throw new ParsinaError(res.status, body);
  cached = { token: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 };
  return cached.token;
}

/** One /v1 call. Renews the token once when the API answers 401. */
export async function api(method, path, { json, idempotencyKey } = {}) {
  for (let attempt = 0; ; attempt++) {
    const headers = { Authorization: `Bearer ${await getToken(attempt > 0)}`, Accept: 'application/json' };
    if (json) headers['Content-Type'] = 'application/json';
    if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;
    const res = await fetch(API + path, {
      method,
      headers,
      body: json ? JSON.stringify(json) : undefined,
      signal: AbortSignal.timeout(20_000),
    });
    const body = await res.json().catch(() => null);
    if (res.status === 401 && attempt === 0) continue;
    return { status: res.status, body, retryAfter: Number(res.headers.get('retry-after')) || null };
  }
}

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

/** Books with retries that can never double-book: the same key and body every time. */
export async function book(clinicId, booking, idempotencyKey) {
  const backoff = [2, 5, 10, 30];
  for (let attempt = 0; ; attempt++) {
    let wait = null;
    try {
      const { status, body, retryAfter } = await api('POST', `/v1/clinics/${clinicId}/bookings`, { json: booking, idempotencyKey });
      if (status === 201 || status === 200) return body; // 200 = a replay of the same request
      const retryable = status === 429 || status >= 500 || body?.error?.code === 'IN_PROGRESS';
      if (!retryable) throw new ParsinaError(status, body);
      wait = retryAfter;
    } catch (err) {
      // A definite refusal is thrown; a 5xx (token 503 included), a timeout or a network
      // failure leaves the outcome unknown, so retry with the SAME key.
      if (err instanceof ParsinaError && !(err.status >= 500)) throw err;
    }
    if (attempt >= backoff.length) {
      throw new Error('No definite answer yet. Retry later with the SAME key; never a new one.');
    }
    await sleep(Math.min(wait ?? backoff[attempt], 60));
  }
}

// ── Usage ───────────────────────────────────────────────────────────────────
const clinicId = 'bc16c5db-ae46-4a03-af3a-515daae06939';
const practitionerId = 'fb4a5808-15ad-45d9-a57c-41fbf6ea73a1';
const serviceId = '38202e35-716e-497a-b15d-bf782de39e02';

const query = new URLSearchParams({ practitionerId, serviceId, mode: 'in_person', from: '2026-12-01', days: '7' });
const free = await api('GET', `/v1/clinics/${clinicId}/availability?${query}`);
if (free.status !== 200) throw new ParsinaError(free.status, free.body);
const slot = free.body.days.flatMap((day) => day.slots)[0];
if (!slot) throw new Error('No free time in this range.');

const booking = await book(clinicId, {
  practitionerId,
  serviceId,
  mode: 'in_person',
  start: slot.start,
  patient: { firstName: 'سارا', lastName: 'محمدی', mobile: '09121234567', relation: 'self' },
  externalRef: 'WP-88412',
}, 'wp-order-88412-1');

// Parsina sends no SMS: confirm to the patient yourself (on screen, SMS, e-mail).
console.log(`نوبت ثبت شد: ${booking.jalali.date} ساعت ${booking.jalali.time} — ${booking.practitioner.displayName}، ${booking.clinic.name}`);

Python (requests)

Python 3.8 or later with requests.

Python
"""Parsina Booking API client: Python 3.8+ with requests. Server side only."""
import os
import time
from urllib.parse import urlencode

import requests

API = "https://gateway.parsinabot.ir"
CLIENT_ID = os.environ["PARSINA_CLIENT_ID"]
CLIENT_SECRET = os.environ["PARSINA_CLIENT_SECRET"]

session = requests.Session()
_token = {"value": None, "expires_at": 0.0}  # one token for every call, renewed 60 s early


class ParsinaError(Exception):
    def __init__(self, status, body):
        err = (body or {}).get("error") or {}
        if isinstance(err, str):  # /oauth/token answers in the RFC 6749 shape
            err = {"code": err, "messageEn": (body or {}).get("error_description")}
        super().__init__(f"{err.get('code') or status}: {err.get('messageEn') or 'request failed'}")
        self.status = status
        self.code = err.get("code")
        self.request_id = err.get("requestId")


def _json(response):
    try:
        return response.json()
    except ValueError:
        return None


def get_token(force_new=False):
    if not force_new and _token["value"] and _token["expires_at"] - 60 > time.time():
        return _token["value"]
    r = session.post(f"{API}/oauth/token", auth=(CLIENT_ID, CLIENT_SECRET),
                     data={"grant_type": "client_credentials"}, timeout=10)
    body = _json(r)
    if r.status_code != 200:
        raise ParsinaError(r.status_code, body)
    _token.update(value=body["access_token"], expires_at=time.time() + body["expires_in"])
    return _token["value"]


def api(method, path, json=None, idempotency_key=None):
    """One /v1 call; renews the token once on 401. Returns (status, body, retry_after)."""
    for attempt in range(2):
        headers = {"Authorization": f"Bearer {get_token(force_new=attempt > 0)}"}
        if idempotency_key:
            headers["Idempotency-Key"] = idempotency_key
        r = session.request(method, API + path, json=json, headers=headers, timeout=20)
        if r.status_code == 401 and attempt == 0:
            continue
        retry_after = r.headers.get("Retry-After", "")
        return r.status_code, _json(r), int(retry_after) if retry_after.isdigit() else None


def book(clinic_id, booking, idempotency_key):
    """Retries that can never double-book: the same key and the same body every time."""
    backoff = [2, 5, 10, 30]
    for attempt in range(len(backoff) + 1):
        wait = None
        try:
            status, body, wait = api("POST", f"/v1/clinics/{clinic_id}/bookings", booking, idempotency_key)
            if status in (200, 201):
                return body  # 200 = a replay of the same request
            code = ((body or {}).get("error") or {}).get("code")
            if not (status == 429 or status >= 500 or code == "IN_PROGRESS"):
                raise ParsinaError(status, body)
        except requests.RequestException:
            pass  # timeout or connection error: outcome unknown, retry with the SAME key
        except ParsinaError as err:
            if err.status < 500:
                raise  # a definite refusal; a 5xx (token 503 included) is retried
        if attempt < len(backoff):
            time.sleep(min(wait or backoff[attempt], 60))
    raise RuntimeError("No definite answer yet. Retry later with the SAME key; never a new one.")


# ── Usage ───────────────────────────────────────────────────────────────────
clinic_id = "bc16c5db-ae46-4a03-af3a-515daae06939"
practitioner_id = "fb4a5808-15ad-45d9-a57c-41fbf6ea73a1"
service_id = "38202e35-716e-497a-b15d-bf782de39e02"

query = urlencode({"practitionerId": practitioner_id, "serviceId": service_id,
                   "mode": "in_person", "from": "2026-12-01", "days": 7})
status, free, _ = api("GET", f"/v1/clinics/{clinic_id}/availability?{query}")
if status != 200:
    raise ParsinaError(status, free)
slots = [slot for day in free["days"] for slot in day["slots"]]
if not slots:
    raise SystemExit("No free time in this range.")

booking = book(clinic_id, {
    "practitionerId": practitioner_id,
    "serviceId": service_id,
    "mode": "in_person",
    "start": slots[0]["start"],
    "patient": {"firstName": "سارا", "lastName": "محمدی", "mobile": "09121234567", "relation": "self"},
    "externalRef": "WP-88412",
}, idempotency_key="wp-order-88412-1")

# Parsina sends no SMS: confirm to the patient yourself (on screen, SMS, e-mail).
print(f"نوبت ثبت شد: {booking['jalali']['date']} ساعت {booking['jalali']['time']} — "
      f"{booking['practitioner']['displayName']}، {booking['clinic']['name']}")

Changelog

v1, 2026-11 (Azar 1405)

  • First release: client-credentials tokens (valid 15 minutes), /v1/me, clinic profile, practitioners, services, free times, create, read, find and cancel bookings, and the OpenAPI document.
  • In-person visits, paid at the clinic.
  • Not yet: online visits, webhooks, rescheduling, services performed by non-practitioner staff, and online payment.

v1 only grows. Any breaking change comes with a new path (/v2).